我正在学习Swift,并在操场上四处乱逛。我有以下字典:
var person = [
"first": "John",
"last": "Smith",
"age": 21
]
Run Code Online (Sandbox Code Playgroud)
我正在使用以下行来打印输出:
"Your first name is \(person["first"]) and you are \(person["age"]) years old."
Run Code Online (Sandbox Code Playgroud)
使用此代码,我得到以下输出:
// -> "Your first name is Optional(John) and you are Optional(21) years old."
Run Code Online (Sandbox Code Playgroud)
我希望收到以下输出:
// -> "Your first name is John and you are 21 years old."
Run Code Online (Sandbox Code Playgroud)
可选来自哪里?为什么这不只是在指定键上打印值?我需要做什么来解决这个问题?
从字典中检索给定键的值始终是可选操作,因为该键可能不存在,则值是nil。使用String Interpolation "\(...)",Optional作为文字字符串包括在内。
为了避免Optional(...)字符串插值中的文字,您必须以安全的方式打开首选的可选内容
if let first = person["first"] as? String, age = person["age"] as? Int {
print("Your first name is \(first) and you are \(age) years old.")
}
Run Code Online (Sandbox Code Playgroud)