λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
⌨️ Language/swift

[Swift] μ˜΅μ…”λ„ 체이닝

by hyebin (Helia) 2024. 3. 26.
λ°˜μ‘ν˜•

μ˜΅μ…”λ„ 체이닝

nil일 μˆ˜λ„ μžˆλŠ” ν”„λ‘œνΌν‹°λ‚˜, λ©”μ†Œλ“œ 그리고 μ„œλΈŒμŠ€ν¬λ¦½νŠΈμ— 질의(query)λ₯Ό ν•˜λŠ” κ³Όμ •

  • λ§Œμ•½ μ˜΅μ…”λ„μ΄ ν”„λ‘œνΌν‹°λ‚˜ λ©”μ†Œλ“œ ν˜Ήμ€ μ„œλΈŒμŠ€ν¬λ¦½νŠΈμ— λŒ€ν•œ 값을 κ°–κ³  μžˆλ‹€λ©΄ κ·Έ 값을 λ°˜ν™˜ν•¨
  • λ§Œμ•½ 값이 nil이라면 nil λ°˜ν™˜

 

κ°•μ œ μ–Έλž˜ν•‘μ˜ λŒ€μ²΄λ‘œμ¨μ˜ μ˜΅μ…”λ„ 체이닝

  • μ˜΅μ…”λ„ κ°’ 뒀에 λ¬ΌμŒν‘œ(?)λ₯Ό λΆ™μ—¬μ„œ ν‘œν˜„ κ°€λŠ₯
  • μ˜΅μ…”λ„μ„ μ‚¬μš©ν•  수 μžˆλŠ” κ°’μ—λŠ” ν”„λ‘œνΌν‹°, λ©”μ†Œλ“œ 그리고 μ„œλΉ„μŠ€ν¬λ¦½νŠΈκ°€ 포함
  • μ˜΅μ…”λ„ 값을 κ°•μ œ μ–Έλž˜ν•‘ν•˜κΈ° μœ„ν•΄ 뒀에 λŠλ‚Œν‘œ(!)λ₯Ό λΆ™μ΄λŠ” 것과 μœ μ‚¬
    • κ°•μ œ μ–Έλž˜ν•‘μ„ ν–ˆλŠ”λ° λ§Œμ•½ κ·Έ 값이 μ—†μœΌλ©΄ λŸ°νƒ€μž„ μ—λŸ¬ λ°œμƒ
    • μ˜΅μ…”λ„ 체이닝을 μ‚¬μš©ν•˜λ©΄ λŸ°νƒ€μž„ μ—λŸ¬ λŒ€μ‹  nil이 λ°˜ν™˜
class Person {
    var residence: Residence?
}

class Residence {
    var numberOfRooms = 1
}

let roomCount = john.residence!.numberOfRooms
// this triggers a runtime error

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

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

 

μ˜΅μ…”λ„ 체이닝을 μœ„ν•œ λͺ¨λΈ 클래슀 μ •μ˜

  • ν•œ 단계가 μ•„λ‹Œ μ—¬λŸ¬ 단계(multi-level optional chaining) μ‚¬μš©ν•  수 있음
class Person {
    var residence: Residence?
}

class Residence {
    var rooms = [Room]()
    var numberOfRooms: Int {
        return rooms.count
    }
    subscript(i: Int) -> Room {
        get {
            return rooms[i]
        }
        set {
            rooms[i] = newValue
        }
    }
    func printNumberOfRooms() {
        print("The number of rooms is \\(numberOfRooms)")
    }
    var address: Address?
}

class Room {
    let name: String
    init(name: String) { self.name = name }
}

class Address {
    var buildingName: String?
    var buildingNumber: String?
    var street: String?

    func buildingIdentifier() -> String? {
        if let buildingNumber = buildingNumber, let street = street {
            return "\\(buildingNumber) \\(street)"
        } else if buildingName != nil {
            return buildingName
        } else {
            return nil
        }
    }
}

 

μ˜΅μ…”λ„ 체이닝을 ν†΅ν•œ ν”„λ‘œνΌν‹°μ˜ μ ‘κ·Ό

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

let someAddress = Address()

someAddress.buildingNumber = "29"
someAddress.street = "Acacia Road"
john.residence?.address = someAddress
  • john.residence?κ°€ nil이기 λ•Œλ¬Έμ— address 할당은 μ‹€νŒ¨ν•¨
  • 할당도 ν• λ‹Ήλ°›λŠ” μ™Όμͺ½ 항이 nil이면 μ•„μ˜ˆ 였λ₯Έμͺ½ 항이 μ‹€ν–‰λ˜μ§€ μ•ŠμŒ
func createAddress() -> Address {
    print("Function was called.")
  let someAddress = Address()
    someAddress.buildingNumber = "29"
    someAddress.street = "Acacia Road"    

    return someAddress
}
john.residence?.address = createAddress()

 

μ˜΅μ…”λ„ 체이닝을 ν†΅ν•œ λ©”μ†Œλ“œ 호좜

func printNumberOfRooms() {
    print("The number of rooms is \\(numberOfRooms)")
}

if john.residence?.printNumberOfRooms() != nil {
    print("It was possible to print the number of rooms.")
} else {
    print("It was not possible to print the number of rooms.")
}
// Prints "It was not possible to print the number of rooms."

if (john.residence?.address = someAddress) != nil {
    print("It was possible to set the address.")
} else {
    print("It was not possible to set the address.")
}
// Prints "It was not possible to set the address."

 

μ˜΅μ…”λ„ 체이닝을 ν†΅ν•œ μ„œλΈŒμŠ€ν¬λ¦½νŠΈ μ ‘κ·Ό

if let firstRoomName = john.residence?[0].name {
    print("The first room name is \\(firstRoomName).")
} else {
    print("Unable to retrieve the first room name.")
}
// Prints "Unable to retrieve the first room name."

let johnsHouse = Residence()
johnsHouse.rooms.append(Room(name: "Living Room"))
johnsHouse.rooms.append(Room(name: "Kitchen"))
john.residence = johnsHouse

 if let firstRoomName = john.residence?[0].name {
    print("The first room name is \\(firstRoomName).")
} else {
    print("Unable to retrieve the first room name.")
}
// Prints "The first room name is Living Room."
  • μ˜΅μ…”λ„ νƒ€μž…μ˜ μ„œλΈŒμŠ€ν¬λ¦½νŠΈ μ ‘κ·Ό
var testScores = ["Dave": [86, 82, 84], "Bev": [79, 94, 81]]
testScores["Dave"]?[0] = 91
testScores["Bev"]?[0] += 1
testScores["Brian"]?[0] = 72
// the "Dave" array is now [91, 82, 84] and the "Bev" array is now [80, 94, 81]

 

 

μ²΄μ΄λ‹μ˜ 닀쀑 레벨 μ—°κ²°

  • μ˜΅μ…”λ„ μ²΄μ΄λ‹μ˜ μƒμœ„ 레벨 값이 μ˜΅μ…”λ„μΈ 경우 ν˜„μž¬ 값이 μ˜΅μ…”λ„μ΄ μ•„λ‹ˆλ”λΌλ„ κ·Έ 값은 μ˜΅μ…”λ„κ°’μ΄ λ©λ‹ˆλ‹€.
  • μ˜΅μ…”λ„ μ²΄μ΄λ‹μ˜ μƒμœ„ 레벨 값이 μ˜΅μ…”λ„μ΄κ³  ν˜„μž¬ 값이 μ˜΅μ…”λ„ 이라고 ν•΄μ„œ 더 μ˜΅μ…”λ„ν•˜κ²Œ λ˜μ§„ μ•ŠμŠ΅λ‹ˆλ‹€.
  • μ˜΅μ…”λ„ 체이닝을 톡해 값을 κ²€μƒ‰ν•˜κ±°λ‚˜ λ©”μ†Œλ“œλ₯Ό ν˜ΈμΆœν•˜λ©΄ λͺ‡ 단계λ₯Ό κ±°μΉ˜λŠ”μ§€ 상관없이 μ˜΅μ…”λ„μ„ λ°˜ν™˜ν•©λ‹ˆλ‹€.
if let johnsStreet = john.residence?.address?.street {
    print("John's street name is \\(johnsStreet).")
} else {
    print("Unable to retrieve the address.")
}
// Prints "Unable to retrieve the address."
let johnsAddress = Address()
johnsAddress.buildingName = "The Larches"
johnsAddress.street = "Laurel Street"
john.residence?.address = johnsAddress

if let johnsStreet = john.residence?.address?.street {
    print("John's street name is \\(johnsStreet).")
} else {
    print("Unable to retrieve the address.")
}
// Prints "John's street name is Laurel Street."

 

μ²΄μ΄λ‹μ—μ„œ μ˜΅μ…”λ„ 값을 λ°˜ν™˜ν•˜λŠ” λ©”μ†Œλ“œ

if let buildingIdentifier = john.residence?.address?.buildingIdentifier() {
    print("John's building identifier is \\(buildingIdentifier).")
}
// Prints "John's building identifier is The Larches."

if let beginsWithThe =
    john.residence?.address?.buildingIdentifier()?.hasPrefix("The") {
    if beginsWithThe {
        print("John's building identifier begins with \\"The\\".")
    } else {
        print("John's building identifier does not begin with \\"The\\".")
		}
}
// Prints "John's building identifier begins with "The"."
λ°˜μ‘ν˜•

'⌨️ Language > swift' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

[Swift] ν”„λ‘œν† μ½œ  (0) 2024.03.29
[Swift] μ—λŸ¬ 처리  (0) 2024.03.28
[Swift] μ΄ˆκΈ°ν™”  (1) 2024.03.25
[Swift] 상속  (0) 2024.03.22
[Swift] μ„œλΈŒμŠ€ν¬λ¦½νŠΈ  (0) 2024.03.22