我在某些 Swift Optional Binding 与强制转换为协议时遇到了问题。我在一个运行良好的操场上有以下代码。
protocol CodeCollection {
var name: String { get }
var codes: [String] { get }
}
struct VirtualDoors: CodeCollection {
var name = "Virtual Doors"
var codes: [String] = ["doorNumba1", "doorNumba2"]
}
// Instance of VirtualDoors
let doors = VirtualDoors()
// cast into Any? like what awake(withContext context: Any?) receives
var context = doors as Any?
print(context)
if let newDoors = context as? CodeCollection {
// Works as expected
print(newDoors)
}
我在 watchKit 中使用与传入的一条信息完全相同的协议和结构,awake(withContext context: Any?)
并且与 cast 的可选绑定在那里失败。
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Just checking to make sure the expected item is in fact being passed in
print(context)
// "Optional(VirtualDoors(name: "Virtual Doors", codes: ["doorNumba1", "doorNumba2"]))\n"
if let newDoors = context as? CodeCollection {
self.collection = newDoors
print("Context Casting Success")
} else {
// Casting always fails
print("Context Casting Fail")
}
}
如果有人能告诉我为什么这在操场上有效,但在 watchKit 类方法中无效,我将不胜感激。
我觉得我错过了一些非常明显的东西。