iOS Swift - Conditional Statement(if/switch/guard)

longlivedrgn·2022년 1월 13일
0

swift문법

목록 보기
1/36
post-thumbnail

if/else 문

if conditon {
statement
} else {
statement
}

let id = "root"
let password = "1234qwer"

// if문 사용
if id == "root" && password == "1234qwer" {
    print("go to admin range")
}
// if문 사용
if id != "root" || password != "1234qwer"{
    print("incorrect")
// if,else 문 사용
if id == "root" && password == "1234qwer" {
    print("go to admin range")
} else{
    print("incorrect")
}

if / else if / else 문

if conditon {
statement
} else if conditon {
statement
} else {
statement
}

let num = 123

// 홀수인 지 짝수인 지 파악하기
if num >= 0 {
    print("positive number")
    if num % 2 == 0 {
        print("positive even number")
    } else {
        print("positive odd number")
    }
} else {
    print("negative number")
}

// 가장 까다로운 조건이 먼저 오게한다!
if num > 100 {
    print("positive number over 100")
} else if num > 10 {
    print("positive number over 10")
} else if num > 0 {
    print("positive number")
} else {
    print("negative")
}

switch 문

기본 switch 문

  • 아래와 같이 number로 저장된 값이 무엇인지 따라서(case에 따라서) 값을 따로 출력할 수 있다.
// switch 문은 모든 경우의 수를 커버해야된다. 따라서 default를 포함해주어야된다!

let number = 1

switch number {
case 1:
   print("일")
case 2, 3:
   print("이 혹은 삼")
default:
   print("나머지")
}

-> 결과 값 : 일

  • 아래와 같이 where를 통하여 조건식을 추가해 줄 수 있다.
switch number {
case let n where n <= 10:
   print(n)
default:
   print("나머지")
}

-> 결과 값 : 1

interval matching

  • 아래와 같이 범위 연산자와 같이 사용할 수 도 있다.
let temperature = -10

switch temperature {
case ..<10:
   print("춥다")
case 11...20:
   print("선선하네~")
case 21...27:
   print("따듯하다!")
case 28... :
   print("덥다!!ㅜㅜ")
default:
   break
}

-> 결과 값 : 춥다

Fall through

  • fall through를 사용하여 그 다음 블럭까지 실행하고 switch문을 종료한다.
let num = 2

switch num {
case 1:
   print("1")
case 2:
   print("2")
   fallthrough
case 3:
   print("3")
case 4:
    print("4")
default:
   break
}

-> 결과 값 : 2 3

  • fallthrough를 통하여 코드 중복을 피할 수 있다.
// 로그인 시도를 12번까지 하면 reset을 하게 한다.

// -> 원래는 아래와 같이 중복된 코드를 사용해되었다.
let attempts = 12

switch attempts {
case ..<12:
   print("로그인 실패!")
case 12:
   print("로그인 실패!")
   print("리셋 되었습니다.")
default:
   print("리셋 되었습니다.")
}


// 그러나 아래와 같이 fallthrough를 사용하면 아래와 같이 코드의 중복을 막을 수 있다.
switch attempts {
case ..<12:
   print("로그인 실패!")
case 12:
   print("로그인 실패!")
   fallthrough
default:
   print("리셋 되었습니다.")
}

-> 결과 값 : 로그인 실패! 리셋 되었습니다.

guard

guard Condition else {
statements
}

  • 즉, guard 이후의 condition이 true이면 else문을 건너뛰고 이후의 코드로 이어나가지만,만약 guard문 의 condition이 false라면, else 문을 실행하고 코드를 중지한다.(return)

  • guard를 사용한 예를 한번 봐보자

func validate(id: String?) -> Bool {
    // optional binding
    guard let id = id else{
        return false
    }
    guard id.count >= 6 else {
        return false
    }
    // 위 코드를 한번에 작성해보자
//    guard let id = id, id.count >= 6 else {
//        return false
//    }
    print("\(id)")
    // 무조건 true를 포함해줘야된다.
    return true
}
  • 만약 문자열을 보내지 않는다면
// 문자열을 넘기지 않을 경우
validate(id: nil)

false

  • 6개 이상의 문자열을 넘길 경우
validate(id:"12345678")

12345678

if문과 guard문의 비교

  • If문
func validateUsingIf() {
    var id: String? = nil
    
    if let str = id {
        if str.count >= 6 {
            print(str)
        }
    }
}
  • guard 문
func validateUsingGuard() {
    var id : String? = nil
    
    guard let str = id else {return}
    guard str.count >= 6 else {return}
    
    print(str)
}

0개의 댓글