I'm having trouble with some Swift Optional Binding with a cast into a protocol. I have the following code in a playground that works fine.
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)
}
I'm using the exact same protocol and struct in watchKit as a piece of info passed in awake(withContext context: Any?)
and the optional binding with cast is failing there.
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")
}
}
I'd be really appreciative if someone could tell me why this is working in the playground but not in the watchKit class method.
I feel like I am missing something really obvious.