How do you downcast an array of protocol instances into AnyObject
s? I've tried some of the more reasonable ideas in the code example below.
protocol Nameable : class {
var name: String { get }
}
class Person: Nameable {
var name: String
init(name: String)
{
self.name = name
}
}
class Example {
func setArray(array: [AnyObject]?, forKey: String)
{
print("hello world")
}
}
var personOne = Person(name: "Evan")
var personTwo = Person(name: "Brian")
var array: [ Nameable ] = [ personOne, personTwo ]
var anotherArray = array.map({ $0 as AnyObject }) // OMG gross!
var yetAnotherArray = array as [ AnyObject ] // Nope.
var evenYetAnotherArray = array as? [ AnyObject ] // Nope.
var omgThisIsAnArray = Array<AnyObject>(array) // Ha ha, srsly. Nope.
var myExample = Example()
myExample.setArray(anotherArray, forKey: "Named")
For what it's worth, setArray(_ anArray: [AnyObject]?, forKey aKey: String)
method signature comes from Apple's NSUbiquitousKeyValueStore
class, so I can't really redesign that to be type safe.