我正在学习斯威夫特并在操场上瞎逛。我有以下词典:
var person = [
"first": "John",
"last": "Smith",
"age": 21
]
我使用以下行打印输出:
"Your first name is \(person["first"]) and you are \(person["age"]) years old."
使用此代码,我得到以下输出:
// -> "Your first name is Optional(John) and you are Optional(21) years old."
我希望收到以下内容作为输出:
// -> "Your first name is John and you are 21 years old."
可选来自哪里?为什么这不是简单地在指定键上打印值?我需要做些什么来解决这个问题?
答案 0 :(得分:5)
从字典中检索给定键的值始终是可选的,因为键可能不存在,然后值为=INDEX(V2, ,)-this is the formula I wrote to Index column V, thus creating column AV
=IFERROR(VLOOKUP("Biscuits",V2:AW2,28,FALSE),"")-This is a formula I wrote to look for "Biscuits" and replace it with the contents of column AW
。使用字符串插值nil
可选包含在文字字符串中。
要避免字符串插值中的文字"\(...)"
,您必须以安全的方式打开首选的选项
Optional(...)
答案 1 :(得分:1)
您的字符串尚未解开并且是可选的,这就是您看到单词optional和括号的原因。如果你想让它们消失,你可以放一个!打开它。但是,我建议以不同的方式处理它,这样你就不会尝试打开零值。
例如,
var person = [
"first": "John",
"last": "Smith",
"age": 21
]
print("Your first name is \(person["first"]) and you are \(person["age"]) years old.")
// prints: "Your first name is Optional(John) and you are Optional(21) years old."
print("Your first name is \(person["first"]!) and you are \(person["age"]!) years old.")
// prints: "Your first name is John and you are 21 years old."
let name = person["first"]!
let age = person["age"]!
print("Your first name is \(name) and you are \(age) years old.")
// prints: "Your first name is John and you are 21 years old."
Vadian有一个很好的例子,说明如何正确打印出来,因为如果你得到的是零,他的例子不会崩溃。
答案 2 :(得分:-1)
尝试像这样做
"Your first name is \(person["first"]!) and you are \(person["age"]!) years old."
然后尝试在这里查看完美的解释Printing optional variable