简体   繁体   中英

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM