如果我创建一个结构数组,一切都按预期工作,但是如果我创建一个结构字典,它们的属性不再可访问,是否有一个额外的步骤来访问它们?请参阅下面的简单示例:
struct SceneStruct {
var number: Int
init(number: Int) {
self.number = number
}
}
let aStruct = SceneStruct(number: 0) //shows in assistant editor as: {number 0}
let bStruct = SceneStruct(number: 26) //shows in assistant editor as: {number 26}
//EXPECTED BEHAVIOR:
let arr = [aStruct,bStruct] //shows in assistant editor as: [{number 0}, {number 26}]
var i = arr[0] //shows in assistant editor as: {number 0}
var j = i.number //shows in assistant editor as: 0
//BROKEN BEHAVIOR:
let dict = ["one": aStruct, "two": bStruct] //shows in assistant editor as: ["one": {number 0}, "two": {number 26}]
var x = dict["one"] //shows in assistant editor as: {{number 0}}
var y = x.number // Fails: "error: 'SceneStruct?' does not have a member named 'number'"
似乎对象以某种方式包装在字典中,但对于我的生活,我找不到有关此行为的任何信息。
答案 0 :(得分:4)
对于数组,下标运算符返回值。
var i = arr[0] // <- i is of type SceneStruct
对于字典,下标运算符返回一个可选字段。
var x = dict["one"] // <- x is of type SceneStruct? (Optional< SceneStruct>)
原因是arr[100]
抛出异常,因为数组超出范围。鉴于dict["invalid"]
返回nil
,查找失败。
您可以通过几种方式解决这种差异。
使用默认值
进行评估var defaultValue = SceneStruct(number: 0)
var x = dict["one"] ?? defaultValue // provide a default value if dict["one"] is nil.
var y = x.number
条件评估
if let x = dict["one"] { // conditionally set x
var y = x.number
} else {
// dict["one"] is nil
}
强制解包
var x = dict["one"]! // force unwrap dict["one"], this will throw an exception if dict["one"] is nil.
var y = x.number
答案 1 :(得分:0)
通过键对字典值进行下标的结果是一个Optional值(在您的情况下为SceneStruct?
)。你需要处理那个可选项。
let dict = ["one": aStruct, "two": bStruct]
let x = dict["one"] // x is SceneStruct?
let y = x?.number // y is Int?