【问题标题】:Swift switch between generics type and protocol conformance在泛型类型和协议一致性之间快速切换
【发布时间】:2017-12-25 19:53:59
【问题描述】:

我想达到这个目标:

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 语言中可以吗?

编辑:

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

class Parser: ParserProtocol {

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

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

【问题讨论】:

    标签: ios swift generics protocols standards-compliance


    【解决方案1】:

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

    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
    

    【讨论】:

    • 这个建议很棒,但不是我想要的。
    猜你喜欢
    • 2021-10-13
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多