• 변수(Variable), 상수(Constant)

//: Playground - noun: a place where people can play

import UIKit

// var는 변수 선언
var str: String = "Hello, playground"
str = "Happy Coding!"
print(str)

// let는 상수
let otherStr = "홍길동"
print("안녕" + otherStr)
print("안녕\(otherStr)")

// Integer
var myInt: Int = 8
print(myInt * 2)
print(myInt + 100)
myInt = myInt + 1
myInt = myInt / 5
print("최종값은 \(myInt)")

let age = 35
print("내이름은 \(otherStr) 그리고 내 나이는 \(age)")

// 실수형 Float(32 bit), Double(64 bit)
var a: Double = 8.73
var b: Float = 8.73
var c = 7.12

print(a / c)

// 서로 자료형이 다를때
print(a / Double(b))
print(Double(myInt) + a)

// Boolean 형
var gameOver = false
print(gameOver)

var gameOverString = String(gameOver)

let d: Double = 5.76
let e: Int = 8
print("The product of \(d) and \(e) is \(d * Double(e))")
  • 배열(Array), 딕셔너리(Dictionary)

//: Playground - noun: a place where people can play

import UIKit

// 배열의 선언 및 생성
var strArray: [Int] = [10, 45, 55]
print(strArray)
strArray.append(100)
print(strArray)
strArray.append(70)
print(strArray)
strArray.insert(60, at: 3)
print(strArray)
strArray.remove(at: 3)
print(strArray)
print("배열의 크기는 \(strArray.count)")
strArray.sort()
print(strArray)

if strArray.contains(10) {
    print("값이 존재한다")
} else {
    print("값이 없다")
}

// empty 배열 사용
var emptyArray = [String]()
print(emptyArray)
emptyArray.append("홍길동")
print(emptyArray)
emptyArray.append("임꺽정")
emptyArray.append("이순신")
print(emptyArray)

// 서로 다른 형의 배열
//var array2: [Any] = ["Swift", 120, true]
var array2 = ["Swift", 120, true] as [Any]

array2.append("23.7")
print(array2)

// Dictionary(사전)
var myDic: [String:String] = ["a":"apple", "b":"banana", "h":"happy"]
print(myDic)

// Dictionary에 element 추가
myDic["c"] = "computer"
print(myDic)
myDic["l"] = "love"
print(myDic)

// Dictionary element 삭제
myDic.removeValue(forKey: "b")
print(myDic)

// empty Dictionary 선언 및 생성
var gameCharacters = [String: [Int]]()
gameCharacters["terran"]=[10, 20, 30]
gameCharacters["zerg"]=[1, 2, 3]
gameCharacters["protoss"]=[100, 200, 300]
print(gameCharacters)

for myKey in gameCharacters {
    print(myKey.key)
    print(myKey.value)
    print(myKey)
//    if myKey.value == 10 {
//        print("\(myKey.key) have maxium energy!")
//    }
}

// force unwraping(강제 뽑기)
//print(gameCharacters["atom"]!)

// optional binding
if let myVal = gameCharacters["atom"] {
    print(myVal)
} else {
    print("nil 발생")
}

//print(gameCharacters["atom"]!)

// optional binding
if let unWrapVal = gameCharacters["atom"] {
    print(unWrapVal)
} else {
    print("nil 발생")
}
  • if, if-esle 문

//: Playground - noun: a place where people can play

import UIKit

let age = 13

// Greater than or equal to

if age >= 18 {
    print ("You can play!")
} else {
    print ("You're too young")
}

// Check username
let name = "rob"
if name == "rob" {
    print ("Hi " + name + "! You can play")
} else {
    print ("Sorry, " + name + ", you can't play")
}

// 2 If Statements With And
if name == "Kim" && age >= 18 {
    print("you can play")
} else if name == "Lee" {
    print("Sorry Lee, you need to get older")
}

// 2 If Statements With Or
if name == "Kim" || name == "Lee" {
    print ("Welcome " + name)
}

// Booleans With If Statements
let isMale = true

if isMale {
    print("You're male!")
}

// Login system. username/password variables. 1. They are correct 2. They are both wrong 
// 3. Username is wrong 4. Password is wrong

let username = "Amadeus"
let password = "12345"

if username == "Amadeus" && password == "12345" {
    print ("You're in!")
} else if username != "Amadeus" && password != "12345" {
    print ("Both username and password are wrong")
} else if username == "Amadeus" {
    print ("Password is wrong")
} else {
    print ("Username is wrong")
}
  • while 루프

//: Playground - noun: a place where people can play

import UIKit

var i = 1

while i <= 10 {
    print (i)
    i += 1
}

// Challenge - display the first 20 numbers in the 7 times table

i = 7

while i <= 140 {
    print (i)
    i += 7
}

// Use a while loop to add one to each of the values in the array

var array = [7, 23, 98, 1, 0, 763]
i = 0

while i < array.count {
    array[i] += 1
    i += 1
}

print (array)
  • for 루프

//: Playground - noun: a place where people can play

import UIKit

let array = [8, 4, 8 , 1]

for number in array {
    print(number)
}

// Create an array with 4 names of friends/family print "Hi there --- !"

let familyMembers = ["Rob", "Kirsten", "Tommy", "Ralphie"]

for familyMember in familyMembers {
    print ("Hi there " + familyMember + "!")
}

var numbers = [7, 2, 9, 4, 1]

for (index, value) in numbers.enumerated() {
    numbers[index] += 1
    print("index = \(index)   value = \(value)")
}

var sum = 0
for i in 0 ..< 10 {
    sum+=1
}
print(sum)

print (numbers)

// array containing 8, 7, 19, 28. Halve each of the values
var myArray = [Double]()
myArray = [8, 7, 19, 28]

for (index, value) in myArray.enumerated() {
    myArray[index] = value / 2
}

print (myArray)
  • 클래스(Class), 객체(Object)

//: Playground - noun: a place where people can play

import UIKit

class Ghost {
    var isAlive = true
    var strength = 9

    func kill() {
        isAlive = false
    }

    func isStrong() -> Bool {
        if strength > 10 {
            return true
        } else {
            return false
        }
    }
}

var ghost1: Ghost = Ghost()
print (ghost1.isAlive)
ghost1.strength = 20
print (ghost1.strength)
ghost1.kill()
print (ghost1.isAlive)
print (ghost1.isStrong())
ghost1.strength = 2
print (ghost1.isStrong())

//////////////////////////////////////////////////////
import UIKit

// 클래스의 정의
class Ghost {
    // 멤버 변수 선언
    var isAlive = true // boolean 변수 - true, false
    var strength = 9
    var name: String?

    func setName(myName: String) -> String {
        name = myName
        return name!
    }

    func kill() {
        isAlive = false
    }

    func isStrong() -> Bool {
        if strength >= 10 {
            return true
        } else {
            return false
        }
    }
}

// 객체 gh1 생성
var gh1 = Ghost() // 생성자 함수(initializer)
var gh2 = Ghost()

gh1.setName(myName: "달걀귀신")
gh2.setName(myName: "팅크벨")

print(gh1.name!)
print(gh2.name!)

print("gh1의 생명상태는 : \(gh1.isAlive)")
gh1.kill()
print("gh1의 생명상태는 : \(gh1.isAlive)")
gh1.strength = 20
print("gh1은 센놈이다 : \(gh1.isStrong())")

//print("gh2의 생명상태는 : \(gh2.isAlive)")
  • optional 변수

//: Playground - noun: a place where people can play

import UIKit

var number: Int?
number = 10

// Force Unwrap(강제풀기)
print (number!)

// optional binding
if let myNum = number {
    print(myNum)
} else {
    print("nil")
}

print(number)
//print(number as Any)

let userEnteredText = "Happy"

//print(Int(userEnteredText)

let userEnteredInteger = Int(userEnteredText)
//print("userEnteredInteger = \(userEnteredInteger!)")

if let catAge = userEnteredInteger {
    print (catAge * 7)
} else {
    print("nil occured")
}
  • 함수(function)

//: Playground - noun: a place where people can play
// Function Bsaic
import UIKit

func nameOfFunction() {
    // body of function goes here
}

// defining the "sayHello" function
func sayHello() {
    print("Hello!")
}

// calling "sayHello"
sayHello()

let myNmae  = "홍길동"

func sayHelloToStudent(student: String) {
    print("Hello, \(student)!")
}

sayHelloToStudent(student: myNmae)

// Functions With Multiple Parameter
func greetStudent(student: String, lateForClass: Bool) {
    if lateForClass {
        print("\(student).. you are late!")
    } else {
        print("Glad you could join us today \(student)")
    }
}

func averageScore(firstScore: Double, secondScore: Double, thirdScore: Double) {
    //body of the function
    let totalScore = firstScore + secondScore + thirdScore
    print(totalScore / 3)
}


// function call
greetStudent(student: "홍길동", lateForClass: false)
greetStudent(student: "임꺽정", lateForClass: true)
greetStudent(student: "이순신", lateForClass: true)

averageScore(firstScore: 70.7, secondScore: 67, thirdScore: 86.5)

// Returning Values
func calculateTip(priceOfMeal: Double) -> Double {
    return priceOfMeal * 0.15
}

func isValidLength(password: String) -> Bool {
    if password.characters.count >= 8 {
        return true
    } else {
        return false
    }
}

let tip = calculateTip(priceOfMeal: 150)
print("tip = \(tip)")

print(isValidLength(password: "12345"))

// Accessing Return Values
func calculateMyTip(priceOfMeal: Double) -> Double {
    return priceOfMeal * 0.15
}

let priceOfMeal = 43.27

let myTip = calculateMyTip(priceOfMeal: priceOfMeal)

// Default Parameter
func calculatePriceForMealWithTip(priceOfMeal: Double, tipPercentage: Double ) -> Double {
    return priceOfMeal + (priceOfMeal * tipPercentage)
}

calculatePriceForMealWithTip(priceOfMeal: 43.27, tipPercentage: 0.15)
calculatePriceForMealWithTip(priceOfMeal: 100.32, tipPercentage: 0.20)
calculatePriceForMealWithTip(priceOfMeal: 65.43, tipPercentage: 0.15)
calculatePriceForMealWithTip(priceOfMeal: 22.18, tipPercentage: 0.15)

func calculateMyPriceForMealWithTip(priceOfMeal: Double, tipPercentage: Double = 0.15) -> Double {
    return priceOfMeal + (priceOfMeal * tipPercentage)
}

// This call uses the default tip of 15% (0.15)
calculateMyPriceForMealWithTip(priceOfMeal: 43.27)
calculateMyPriceForMealWithTip(priceOfMeal: 100.32, tipPercentage: 0.20)
calculateMyPriceForMealWithTip(priceOfMeal: 65.43)
calculateMyPriceForMealWithTip(priceOfMeal: 22.18)

// Chaining Functions
func addExcitementToString(string: String) -> String {
    return string + "!"
}

// chained together twice
let excitedString = addExcitementToString(string: addExcitementToString(string: "yay"))

// chained together 4 times
let reallyExcitedString = addExcitementToString(string: addExcitementToString(string: addExcitementToString(string: addExcitementToString(string: "wahoo"))))


// sum of array
import UIKit

let array = ["A", "13", "B", "5", "87", "t", "41"]

class Arithmetic {
    func somOfString(inputOfStrings: [String]) -> Int {
        let array = inputOfStrings
        var sum = 0
        for myString in array {
            if Int(myString) != nil {
                let intToAdd = Int(myString)!
                sum += intToAdd
            }
        }
        return sum
    }
}

var calculator = Arithmetic()
calculator.somOfString(inputOfStrings: array)
  • 코딩 실습 : 소수(prime number) 구하기

// playground coding
import UIKit

let number = 17

var isPrime = true

if number == 1 { 
    isPrime = false
}

var i = 2

while i < number {   
    if number % i == 0 {
        isPrime = false
    }
    i += 1
}

print(isPrime)

//  ViewController.swift
//  Is It Prime

import UIKit

class ViewController: UIViewController {

    @IBOutlet var numberTextField: UITextField!
    @IBOutlet var resultLabel: UILabel!

    @IBAction func isItPrime(_ sender: AnyObject) {        
        if let userEnteredString = numberTextField.text {
            let userEnteredInteger = Int(userEnteredString)
            if let number = userEnteredInteger {

                var isPrime = true
                if number == 1 {
                    isPrime = false
                }

                var i = 2

                while i < number {    
                    if number % i == 0 {
                        isPrime = false
                    }
                    i += 1
                }

                if isPrime {                    
                    resultLabel.text = "\(number) is prime!"
                } else {
                    resultLabel.text = "\(number) is not prime"
                }

            } else {
                resultLabel.text = "Please enter a positive whole number"
            }
        }  
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

results matching ""

    No results matching ""