簡體   English   中英

Swift Casting to a protocol 返回 nil

[英]Swift Casting to a protocol returns nil

我有一些屬於一種協議類型的值的數組。 我需要將這些值轉換為另一種協議類型,以便我可以從中訪問該方法。 但是鑄造對我來說是零。 為什么? 從一種協議類型轉換為另一種協議類型的條件是什么?

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
}

要回答您的最后一個問題,您可以轉換為第一個協議擴展的另一個協議,或者兩者都實現相同的協議。 考慮下面的例子

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM