gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:17:29 26 4
gpt4 key购买 nike

我想实现这个目标:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com