当我使用字典条目作为变量打印字符串时,为什么要添加“可选”一词?

oto*_*ock 1 dictionary swift

我正在学习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)

可选来自哪里?为什么这不只是在指定键上打印值?我需要做什么来解决这个问题?

vad*_*ian 5

从字典中检索给定键的值始终是可选操作,因为该键可能不存在,则值是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)

  • 空合并运算符`??`在这里也很方便,以在属性为'nil'时提供默认值。例如`print(“您的名字是\(person [” first“] ??”未知“),而您是\(person [” age“] ??”未知数“)岁。”) (2认同)