致命错误铸造类型数组协议时:不能从Objective-C的桥接 [英] Fatal error when casting array of types to protocols: cannot be bridged from Objective-C
问题描述
有<一个href=\"http://stackoverflow.com/questions/25588196/protocol-typed-array-cant-be-downcast-to-concrete-type-array\">similar问题,在那里,但是这一次是对雨燕最新的2.2版本。希望有现在一个解决方案,因为这似乎是在我脑海中的一大障碍面向协议编程
。
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.
下面的失败对分配给让结果
一个错误:执行被中断,原因是:EXC_BAD_INSTRUCTION(code = EXC_I386_INVOP,分code = 0X0)。
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()
有没有什么办法来治疗类数组作为协议的阵列,它符合?这似乎是一个语言尤其是一个沉重是一个非常简单的和自然的要求协议为本
。
我不希望使用 @objc
或 flatMap
因为依赖链和广阔的性能影响 - 这将是一个黑客。我想这本身工作或那就是我们希望能制定和present苹果/斯威夫特开源团队的错误。
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.
推荐答案
可能是我不明白你的问题,但这个作品
may be i don't understand your question, but this works
protocol P: class {
var value:Int {get}
}
class X: P {
var value = 0
init(_ value:Int) {
self.value = value
}
}
func getItems() -> [P] {
let items: [P] = [X(1), X(2), X(3)]
return items
}
let results = getItems()
results.forEach { (p) in
print(p.value)
}
/*
1
2
3
*/
为什么铸造[X]为[P]不起作用?参见下面的例子中!
why casting [X] as [P] doesn't work? See the next example!
protocol P: class {
var value:Int {get}
}
protocol P1: class {
var value: Double { get }
}
protocol Z {}
class X: P,Z {
var value = 0
init(_ value:Int) {
self.value = value
}
}
class X1: P1,Z {
var value = 0.0
init(_ value:Double) {
self.value = value
}
}
func getItems() -> [Z] {
// the only common type of all items is protocol Z !!!!
let items: [Z] = [X(1), X(2), X(3), X1(1), X1(2)]
return items
}
let results = getItems()
print(results.dynamicType)
results.forEach { (p) in
if let p = p as? P {
print("P:", p.value)
}
if let p = p as? P1 {
print("P1:", p.value)
}
}
/*
Array<Z>
P: 1
P: 2
P: 3
P1: 1.0
P1: 2.0
*/
这是什么原因,为什么使用flatMap是不错的主意,如果你想分开结果X和X1型项目
that is the reason, why using flatMap is good idea, if you would like to separate X and X1 type items from results
let arrX = results.flatMap { $0 as? P }
let arrX1 = results.flatMap { $0 as? P1 }
print(arrX, arrX1) // [X, X, X] [X1, X1]
这篇关于致命错误铸造类型数组协议时:不能从Objective-C的桥接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!