【问题标题】:Swift Casting to a protocol returns nilSwift Casting 到协议返回 nil
【发布时间】:2019-03-05 11:33:16
【问题描述】:

我有一些属于一种协议类型的值的数组。我需要将这些值转换为另一种协议类型,以便我可以从中访问方法。但是铸造对我来说是零回报。为什么? 从一种协议类型转换为另一种协议类型的条件是什么?

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
}

【问题讨论】:

  • 为你的代码提供强制转换方法
  • "从一种协议类型转换为另一种协议类型的条件是什么?" - 对象必须符合两种协议
  • 请添加一些代码
  • 你昨天不是问了同样的问题还是用了一些代码?你为什么不回复那个问题中的 cmets 而不是删除它?
  • 类型转换不会将一种类型的对象转换为另一种类型,它只是告诉编译器您希望在特定时间如何处理给定对象。 dog.getAnimals() 实际上并没有返回一个 Source 的数组,它返回一个符合 Source 协议的类或结构的数组。为了将其中一个东西转换为Map,类或结构必须符合Map以及Source

标签: ios swift prototype protocols typecasting-operator


【解决方案1】:

要回答您的最后一个问题,您可以转换为第一个协议扩展的另一个协议,或者如果两者都实现相同的协议。考虑下面的例子

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
}

【讨论】:

  • 谢谢,我会试试上面的代码。但是我们的项目中不允许强制转换。
  • 这只是一个简单的例子,因此强制转换而不是更合适的实现
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-05
  • 2018-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多