There's similar questions out there, but this one is on the latest Swift 2.2 version. Hopefully there's a solution by now because this seems like a big obstacle to Protocol-Oriented Programming
in my mind.
The below fails on assigning to let results
with an error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0X0).
protocol P: class {
var value:Int {get}
}
class X: P {
var value = 0
init(_ value:Int) {
self.value = value
}
}
func getItems() -> [P] {
let items: [X] = [X(1), X(2), X(3)]
return items
}
let results: [P] = getItems()
Is there any way to treat an array of classes as an array of protocols that it conforms to? This seems like a really simple and natural request for a language especially one that is heavily protocol-oriented
.
I don't want to use @objc
or flatMap
because of vast implications on the dependency chain and performance - this would be a hack. I'd like this to work natively or it's a bug that we can hopefully formulate and present to Apple / Swift open-source team.