iOS 응용 (swift)
[iOS - swift] dictionary nil 초기화 시 주의사항
jake-kim
2023. 12. 23. 22:02
Dictionary 초기화 시 주의사항
- dictionary: key - value 쌍으로 데이터를 저장할 수 있는 형태
- dictionary 값을 초기화하는 방법에 대해서 명확히 알고 있어야 사용할때 혼동이 생기지 않음
초기화 방법
- key-value 모두 날리고 싶은 경우
- dictinoary 대괄호 안에 key값을 넣고, 오른쪽에 nil을 대입
var dict: [Int: String?] = [1: "1", 2: "2", 3: "3"]
dict[1] = nil
// [2: Optional("2"), 3: Optional("3")]
or removeValue(forKey:) 사용
var dict: [Int: String?] = [1: "1", 2: "2", 3: "3"]
dict.removeValue(forKey: 1)
// [2: Optional("2"), 3: Optional("3")]
- key값은 삭제하지 않고, value 값만 nil로 바꾸고 싶은 경우
- updateValue(nil, forKey:) 사용
dict.updateValue(nil, forKey: 2)
print(dict)
// [2: nil, 3: Optional("3")]