swift的泛型也是使用<>的形式
func genericFunc<Item>(repeatItem item:Item,numberOfLoop:Int)->[Item] { var result = [Item]() for _ in 0..<numberOfLoop { result.append(item) } return result } var result1 = genericFunc(repeatItem: "LMC",numberOfLoop: 5) print(result1) var result2 = genericFunc(repeatItem: 1,numberOfLoop: 5) print(result2) var date = Date.init(timeInterval: 0,since: Date()) var result3 = genericFunc(repeatItem: date,numberOfLoop: 5) print(result3)
enum EnumGeneric<Wrapped> { case success case failer(Wrapped) } var generic:EnumGeneric<String> = .success generic = .failer("Hello")
这里还有一个关键字是where需要提一下 where
在我们的方法体开始的前面 我们可以使用where 对参数做出一些约束 比如必须是实现了某一个协议 具有一个特定的父类
func genericWhere<T1,T2>(t1:T1,t2:T2)->Void where T1:ProtocolForGeneric,T2:SuperClassForGeneric{ print(t1.discription) print(t2.discription) }
这里就是 参数t1必须是实现了ProtocolForGeneric协议的 t2的父类是SuperClassForGeneric的
完整的写上代码
protocol ProtocolForGeneric { var discription:String{ get } func hello() } class SuperClassForGeneric { var discription = "SuperClass" func hello() { } } func genericWhere<T1,T2:SuperClassForGeneric{ print(t1.discription) print(t2.discription) } class SubClassForGeneric:SuperClassForGeneric { override init() { super.init() self.discription = "SubClassDiscription" } override func hello() { } } class ClassForGeneric: ProtocolForGeneric { var discription: String = "ProtocolDiscription" func hello() { } } genericWhere(t1: ClassForGeneric.init(),t2: SubClassForGeneric.init())原文链接:https://www.f2er.com/swift/322963.html