[swift] Swift 딕셔너리에서 키와 값을 신뢰성 있게 처리하는 방법은?

다음은 Swift에서 딕셔너리의 키와 값을 안전하게 처리하는 방법입니다.

// 딕셔너리 선언
var dictionary: [String: Int] = ["apple": 5, "banana": 3, "orange": 7]

// 옵셔널 체이닝을 사용하여 키에 대한 값 가져오기
if let appleCount = dictionary["apple"] {
    print("Apple count: \(appleCount)")
} else {
    print("Apple count not found")
}

// 옵셔널 바인딩을 사용하여 값을 업데이트하기
if var orangeCount = dictionary["orange"] {
    orangeCount += 2
    dictionary["orange"] = orangeCount
    print("Updated orange count: \(dictionary["orange"]!)")
} else {
    print("Orange count not found")
}

위의 예시에서는 옵셔널 체이닝과 옵셔널 바인딩을 사용하여 딕셔너리의 키와 값을 안전하게 처리하는 방법을 보여줍니다. 코드를 실행하면 딕셔너리의 키와 값을 신뢰성 있게 처리할 수 있습니다.

더 많은 정보를 원한다면 Swift 공식 문서를 참조하세요 Swift 공식 문서.