Apple-CS-interview / iOS-CS-interview

7 stars 0 forks source link

Optional Chaining과 nil-coalescing operator(??)의 차이점과 사용 시 주의사항은 무엇인가요? #33

Open Do-hyun-Kim opened 9 months ago

Do-hyun-Kim commented 9 months ago

Optional Chaining과 nil-coalescing operator(??)의 차이점과 사용 시 주의사항은 무엇인가요?

⛓️ Optional Chaining

import Foundation

class Person {
    var residence: Residence?
}

class Residence {
    var numberOfRooms = 1
}

let john = Person()

let roomCount = john.residence!.numberOfRooms
// run time error : Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

if let roomCount = john.residence?.numberOfRooms {
    print("John's residence has \(roomCount) room(s).")
} else {
    print("Unable to retrieve the number of rooms.")
}

john.residence = Residence()
print(john.residence?.numberOfRooms) //Optional(1)

❓ nil-coalescing operator

let defaultValue: Int = 1 // 1

var someOptionalInt: Int? // nil

var myNum = someOptionalInt ?? defaultValue // 1

🧑‍💻 Optional Chaining과 nil-coalescing operator의 차이점과 사용 시 주의사항

📝 참고 사이트

vichye-1 commented 9 months ago

Optional Chaining이란?

struct Address {
    var email: String
    var phone: String
}

struct Human {
    var name: String
    var info: Address

    init(name: String, email: String, phone: String) {
        self.name = name
        info = Address(email: email, phone: phone)
    }
}

var me: Human? = Human(name: "knockknock", email: "knock@naver.com", phone: "010-1234-5678")

me?.info.phone  // "010-1234-5678"

me = nil
me?.info.phone  // nil

nil-coalescing operator(nil 병합 연산자)란?

var name: String? = "knockknock"

// 기존 옵셔널 바인딩 이용
if let name = name {
    print("hello, \(name)")
} else {
    print("hello, what's your name?")
}

// Nil-coalescing 이용
// 1. name에 값이 있는 경우
print("hello, " + (name ?? "what's your name?")) // hello, knockknock

name = nil
// 2. name에 값이 없는 경우
print("hello, " + (name ?? "what's your name?"))  // hello, what's your name?

optional chaining과 nil-coalescing operator의 차이점

사용시 주의사항

struct Address {
    var email: String
    var phone: String?
}

struct Human {
    var name: String
    var info: Address

    init(name: String, email: String, phone: String) {
        self.name = name
        info = Address(email: email, phone: phone)
    }
}

var me: Human? = Human(name: "knockknock", email: "knock@naver.com", phone: "010-1234-5678")

me?.info.phone?  // (X) error : '?' must be followed by a call, member lookup, or subscript

me?.info.phone // (O) "010-1234-5678"

me?.info.phone?.count  // (O) 13
me = nil
me?.info.phone  // nil
// me가 nil이므로 info, phone 표현식은 평가하지 않고 nil을 리턴하여 바로 종료한다.

참고