如何在 swift 中实例化具有不同类型的同一泛型协议的多个实例?
How to instantiate multiple instances of the same generic protocol with different types in swift?
我有一个通用协议 P,我希望其他 class B 拥有该协议的不同类型的不同实例。我想模拟以下行为:
protocol P<T> {
func getAll() -> [T]
}
class B {
var foo1: P<Int>
var foo2: P<String>
}
如何在 swift 中完成此操作?
Swift 中的协议无法做到这一点。你可以做类似的事情:
protocol P {
typealias T
func getAll() -> [T]
}
class C : P {
typealias T = Int
func getAll() -> [T] {
return []
}
}
class D : P {
typealias T = String
func getAll() -> [T] {
return []
}
}
struct B {
var foo1: C
var foo2: D
}
这是您想要完成的吗?
protocol P {
typealias T
func getAll() -> [T]
}
class IntGetter: P {
typealias T = Int
func getAll() -> [T] {
return [1,2,3]
}
}
class StringGetter: P {
typealias T = String
func getAll() -> [T] {
return ["a", "b", "c"]
}
}
let i = IntGetter()
i.getAll() // [1,2,3]
let s = StringGetter()
s.getAll() // ["a","b","c"]
可能这就是您要找的:
protocol P {
typealias T
func getAll() -> [T]
}
extension Int: P {
func getAll() -> [Int] {
return [1, 2, 3]
}
}
extension String: P {
func getAll() -> [String] {
return ["foo", "bar", "zoo"]
}
}
class B {
var foo1: Int = 0
var foo2: String = ""
}
let x = B()
x.foo1.getAll()
x.foo2.getAll()
我有一个通用协议 P,我希望其他 class B 拥有该协议的不同类型的不同实例。我想模拟以下行为:
protocol P<T> {
func getAll() -> [T]
}
class B {
var foo1: P<Int>
var foo2: P<String>
}
如何在 swift 中完成此操作?
Swift 中的协议无法做到这一点。你可以做类似的事情:
protocol P {
typealias T
func getAll() -> [T]
}
class C : P {
typealias T = Int
func getAll() -> [T] {
return []
}
}
class D : P {
typealias T = String
func getAll() -> [T] {
return []
}
}
struct B {
var foo1: C
var foo2: D
}
这是您想要完成的吗?
protocol P {
typealias T
func getAll() -> [T]
}
class IntGetter: P {
typealias T = Int
func getAll() -> [T] {
return [1,2,3]
}
}
class StringGetter: P {
typealias T = String
func getAll() -> [T] {
return ["a", "b", "c"]
}
}
let i = IntGetter()
i.getAll() // [1,2,3]
let s = StringGetter()
s.getAll() // ["a","b","c"]
可能这就是您要找的:
protocol P {
typealias T
func getAll() -> [T]
}
extension Int: P {
func getAll() -> [Int] {
return [1, 2, 3]
}
}
extension String: P {
func getAll() -> [String] {
return ["foo", "bar", "zoo"]
}
}
class B {
var foo1: Int = 0
var foo2: String = ""
}
let x = B()
x.foo1.getAll()
x.foo2.getAll()