5: conditions

그루두·2024년 4월 13일
0

100 days of SwiftUI

목록 보기
7/108

100 days of swiftui: 5
https://www.hackingwithswift.com/100/swiftui/5

if

var age = 20

if age >= 20 && age <= 29 {
    print("You're twenties!")
}


var name1 = "apple"
var name2 = "banana"

if name1 > name2 {
    print("\(name2) -> \(name1)")
}
if name1 < name2 {
    print("\(name1) -> \(name2)")
}


var members = [5, 6, 7]
members.append(8)

if members.count > 3 {
    members.remove(at: 0)
}


if !members.isEmpty {
    print("Members are here!")
}

위처럼 다양하게 if 조건문을 사용할 수 있다. String끼리 부등호로 비교하면 알파벳 순서를 기준으로 참 거짓 여부를 리턴한다. 예시로 apple과 banana를 비교하면 banana가 순서상으론 더 크다. 그리고 특정 데이터의 값 여부를 count나 ""처럼 빈 텍스트로 비교하는 것보다 method인 .isEmpty를 활용하는 것이 더 좋다.

코드 파일
https://github.com/soaringwave/Ios-studying/commit/3a25eaa45a2e6efb8b79a13a51b65266709c2fa1

else if, else

enum Color {
    case red, green, yellow
}

var color = Color.green

if color == .red {
    print("Don't go now")
} else if color == .yellow {
    print("Slow your pace")
} else {
    print("You may go")
}

&&(and), ||(or)

var isWet = true
var isCold = true
var isSunny = false

if isCold && isWet {
    print("It can be winter!")
    if !isSunny {
        print("And it's cold!")
    }
}

코드 파일
https://github.com/soaringwave/Ios-studying/commit/8f2f861e7bd393e9b58716764cf5bdf6c368a82c

switch

한 데이터의 값을 확인하고 그에 따른 조건물을 실행할 땐 if, else보다 switch가 더 유용하다.

let forecast = Weather.unknown

switch forecast {
case .sun:
    print("It should be a nice day.")
case .rain:
    print("Pack an umbrella.")
case .wind:
    print("Wear something warm")
case .snow:
    print("School is cancelled.")
case .unknown:
    print("Our forecast generator is broken!")
}

위는 forcast가 각 case일 때 : 이후의 문장을 실행한다.

swift에서 switch는 두가지 특징이 있다.
1. 데이터에 해당하는 값을 모두 case로 확인해야 한다.
2. 데이터의 값에 해당하면 그 조건문을 실행하고 switch문을 벗어난다.

  1. 만약 switch문에서 확인하고 싶은 데이터가 String이라면 enum과 달리 모든 case를 확인하는 방법을 만들 수 없다. 그대신 default를 이용하여 설정한 case에 해당하지 않았을 때 실행할 수 있는 문장들을 설정할 수 있다.
let place = "Metropolis"

switch place {
case "Gotham":
    print("You're Batman!")
case "Mega-City One":
    print("You're Judge Dredd!")
case "Wakanda":
    print("You're Black Panther!")
default:
    print("Who are you?")
}
  1. 만약 데이터에 해당하는 case 이후의 case에 해당하는 문장들을 모두 실행하고 싶다면 fallthrough를 사용하면 된다.
let day = 2
print("My true love gave to me…")

switch day {
case 5:
    print("5 golden rings")
    fallthrough
case 4:
    print("4 calling birds")
    fallthrough
case 3:
    print("3 French hens")
case 2:
    print("2 turtle doves")
    fallthrough
default:
    print("A partridge in a pear tree")
}

결과:

2 turtle doves
A partridge in a pear tree

코드 파일
https://github.com/soaringwave/Ios-studying/commit/4f489bc566cc0c82448681877dfd94848bd3c0a3

ternary conditional operator

ternary operator: 삼항 연산자

var haveWater = true
print(haveWater ? "Let's drink water!" : "I'm thirsty")


enum Theme {
    case light, dark
}

let theme = Theme.dark

let background = theme == .dark ? "black" : "white"
print(background)

이런 식으로 [조건문] ? [조건문이 true일 때 가지는 값] : [조건문이 false일 때 가지는 값]으로 다른 조건문보다 간단하게 설정할 수 있다.

코드 파일
https://github.com/soaringwave/Ios-studying/commit/0cb95dfea69b7e6847e6a82ce6f7a0c1408828fd

profile
계속 해보자

0개의 댓글

관련 채용 정보