[英]Swift Casting to a protocol returns nil
I have array of some values which are of one protocol type.我有一些属于一种协议类型的值的数组。 I need to cast those values to another protocol type so that I can access the method from it.
我需要将这些值转换为另一种协议类型,以便我可以从中访问该方法。 But casting is returning nil for me.
但是铸造对我来说是零。 Why?
为什么? What are the conditions to cast from one protocol type to another Protocol type?
从一种协议类型转换为另一种协议类型的条件是什么?
Protocol Source: CustomStringConvertible, InputDescribeable {
func getAnimals() -> [Source]}
Protocol Map {
func MapTOAnimal() -> ProtocolX
}
Class Test {
let try = dog.getAnimals() // I have 4 values here of type [Source]
let trytry = try as? Map // returns nil
let needed = trytry.MapToAnimal
}
To answer your last question, you can cast to another protocol that the first protocol extends or if both implement the same protocol.要回答您的最后一个问题,您可以转换为第一个协议扩展的另一个协议,或者两者都实现相同的协议。 Consider the following example
考虑下面的例子
protocol A: CustomStringConvertible {
func doA() -> Void
}
protocol B: A {
func doB() -> Void
}
protocol C: CustomStringConvertible {
func doC() -> Void
}
let arrB = [B]()
let arrA = arrB as! [A]
let arrC = [C]()
let arrD = arrC as! [A]
for b in arrB {
b.doB()
b.doA()
}
for a in arrA {
a.doA()
//a.doB() compilaion error
}
for c in arrC {
c.doC()
let descr = c.description
}
for d in arrD {
// d.doC() compilaion error
let descr = d.description
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.