[swift] guard 문을 사용하여 딕셔너리의 특정 키의 존재 여부를 검사할 수 있나요?

아래는 guard 문을 사용하여 특정 키의 존재 여부를 확인하는 예제입니다.

let myDictionary: [String: Int] = ["key1": 100, "key2": 200]

func processDictionaryValue(forKey key: String) {
    guard let value = myDictionary[key] else {
        print("Key '\(key)' does not exist in the dictionary")
        return
    }
    // 키가 존재하는 경우에 해당하는 동작을 수행합니다.
    print("Value for key '\(key)': \(value)")
}

processDictionaryValue(forKey: "key1") // 출력: Value for key 'key1': 100
processDictionaryValue(forKey: "key3") // 출력: Key 'key3' does not exist in the dictionary

위 예제에서 guard 문은 myDictionary에서 주어진 key에 해당하는 값이 존재하는지 확인합니다. 값이 존재하면 guard 문을 통과하고, 값이 존재하지 않을 경우 메시지를 출력하고 현재 범위를 종료합니다.

guard 문을 사용하면 코드를 읽기 쉽고 간결하게 작성할 수 있으며, 예외적인 상황을 처리하는 데 유용합니다.