swift

swift - Dictionary #2 (Adding Keys and Values)

행복하게사는게꿈 2021. 1. 7. 04:04

Adding Keys and Values

var words = [String: String]()

words["A"] = "Apple"
words["B"] = "Banana"

words.count
words

// 기존 값 대치
words["B"] = "Ball"

// 같은 값 메소드로
// 첫번째 파라미터 : value, 두번째 파라미터 : key
words.updateValue("City", forKey: "C") // 기존에 없는 키면 return nil
words.updateValue("Circle", forKey: "C") // 기존에 잇는 키면 기존 return value -> insert + update = upsert

Removing Keys and Values

// 간단한 방법은 subscript로 구현

// 해당 요소 삭제
words["B"] = nil

// 메소드로 삭제
words.removeValue(forKey: "A")
words.removeValue(forKey: "A")

words.removeAll()