#33: Dictionary Subscript with Default Value
Question
// Swift Quiz
— objc.io (@objcio) October 9, 2019
var messages = [200: "OK",
404: "Not Found"]
var foo: (Int) -> String = { code in
if code > 500 {
return "Server"
}
return "Unknown"
}
let message = messages[300, default: foo(300)]
// What’s the value of message?
Solution
Solution: Unknown
— objc.io (@objcio) October 11, 2019
When we use the dictionary subscript with `default:`, it evaluates and returns the default value in case a key doesn't exist.
See also: https://t.co/IcX3USrWFShttps://t.co/s7500CWmAg