Swift) if-else, 반복문(for, for-in, while ..)

2019. 10. 6. 15:26Swift

반응형

*if else

 

var optionalString: String? = nil

print(optionalString == nil) //true

 

var greeting = "Hello"

if let name = optionalString{

    greeting = "Hello, \(name)"

}else{

    greeting = "Hello, stranger"

}

print(greeting); //Hello, stranger

 

var optionalString2: String? = "jason"

print(optionalString2 == nil) //false

//print(optionalString2) //만약 optional변수를 그냥 print할경우 -> let변수 사용해야함

//경고발생 expession implicitly coerce from 'String' to 'Any'

//Opitinal("jason")

 

var greeting2 = "Hello"

if let name2 = optionalString2{

    greeting2 = "Hello, \(name2)"

}else{

    greeting2 = "Hello, stranger"

}

print(greeting2); //Hello, jason

 

//Way to handle optional values is to provide a default value using ths ?? operator.

//If the optional value is missing, the default value is used instead.

let nickName: String? = nil

let fullName: String? = "John"

let informalGreeting = "Hi \(nickName ?? fullName)" //Hi Optional("John")

 

*Swich

let vegetable = "red pepper"

switch vegetable{

case "celery":

    print("celery")

case "cucumber","watercress":

    //swift는 케이스문 후에 바로 break하기 때문에, case 1: case 2: 이런식으로 사용하면 안됨

    print("cucumber or watercress")

case let x where x.hasSuffix("pepper"): //Notice how let can be used in a pattern to assign the value that matched the pattern to a constant

    print("Is it a spicy \(x)?")

default: //만약 swich문에 default값이 없으면, 해당하는 case가 있어도 에러발생함

    print("default")

}

//Is it a spicy red pepper?

 

*for-in

//to iterate over items in a dictionary by providing a pair of names to use for each key-value pair. Dictionaries are an unordered collection, so their keys and values are iterated over in an arbitrary order.

 

let interestingNumbers = [

    "Prime": [2, 3, 5, 7, 11, 13],

    "Fibonacci": [1, 1, 2, 3, 5, 8],

    "Square": [1, 4, 9, 16, 25]

]

var largest = 0

 

//for (kind, numbers) in interestingNumbers {

 //Immutable value 'kind' was never used; consider replacing with '_' or removing it

 // 사용하지 않을 변수는 유의미한 변수(kind)대신 무의미(_)로 사용하길 권장(에러 x, 경고 o)

for (_, numbers) in interestingNumbers {

    for number in numbers {

        if number > largest {

            largest = number

        }

    }

}

print(largest) //25

 

*While, repeat While

//While 처음부터 조건충족되야 실행

var n = 2

while n < 2 {

    n *= 2

}

print(n)//2

 

//repeat wile( do-while처럼 최초 한번은 실행후에 조건 비교

var m = 2

repeat {

    m *= 2

    

} while m < 2

print(m)//4

 

//Use ..< to make a range that omits its upper value, and use ...to make a range that includes both values.

var total = 0

for i in 0..<4 {

    print("first : \(i)") //0~3 출력

}

for i in 0...4 {

    print("second : \(i)") //0~4 출력

}

반응형

'Swift' 카테고리의 다른 글

Swift) object & class  (0) 2019.12.01
Swift) function  (0) 2019.12.01
Swift) 변수, 상수, 배열, Dictionary  (0) 2019.09.29