我要达到这个目标:

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]
}

最佳答案

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

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

10-04 14:07