ios - 在泛型类型和协议(protocol)一致性之间快速切换

标签 ios swift generics protocols standards-compliance

我想实现这个目标:

func parse<T>(element: Any?) -> [T] {
   // if T is kind of MyProtocol, return get result
   // else 
   let array = [T]()
   //do some stuff
   return array
}
func get<T: MyProtocol>(obj: Any?) -> [T] {
   return //some other stuffs
}

用 Swift 语言可以吗?

编辑:

我有一个类,比如说解析器,它有一些属性。我想要一个独特的函数签名,但执行的代码必须在属性类型的基础上有所不同。

class Parser: ParserProtocol {

    let property1 : [MyClass1] = parse(element: elem1)
    let property2 : [MyClass2] = parse(element: elem2)
}

protocol ParserProtocol {
    func parse<T>(element: Any?) -> [T]
}

最佳答案

这是你可以使用的东西吗?

protocol GenericsTypeProtocol {
    func callParseLogic() -> Void
}

protocol MyProtocol : GenericsTypeProtocol {}

extension GenericsTypeProtocol {
    func callParseLogic() -> Void {
        print("Generic logic called")
    }
}

extension GenericsTypeProtocol where Self : MyProtocol {
    func callParseLogic() -> Void {
        print("MyProtocol logic called")
    }
}

class GenericClass : GenericsTypeProtocol { }
class MyClass : MyProtocol { }
class MixedClass : GenericsTypeProtocol, MyProtocol {}

let a = GenericClass()
a.callParseLogic() //prints: Generic logic called

let b = MyClass()
b.callParseLogic() //prints: MyProtocol logic called

let c = MixedClass()
c.callParseLogic() //prints: MyProtocol logic called

关于ios - 在泛型类型和协议(protocol)一致性之间快速切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45209261/

相关文章:

cocoa-touch - 第一次点击 UITextField 时发生奇怪的崩溃

ios - 使用 Swift 从字典数组创建对象数组

java - 如何从通配符类型变为参数化类型?

c# - 泛型的循环依赖

iphone - 如何为 ImageView 数组中的三个 ImageView 添加 UIPanGestureRecognizer?

ios - 向 SKScene 添加点(如 UIPageViewController 中的点)

ios - 插页式广告后更改场景 (SpriteKit)

objective-c - 如何在 Revenuecat 上使用 1 个以上的产品?

c# - 使用 Type 参数作为返回类型

ios - 使用深度链接启动时应用程序未按预期启动