I have a generic protocol P, and I want other class B to have different instances of this protocol with different types. I want to simulate the following behavior:
protocol P<T> {
func getAll() -> [T]
}
class B {
var foo1: P<Int>
var foo2: P<String>
}
How can I accomplish this in swift?
You can't do that with protocols in Swift. You can do something similar:
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
}
Probably this is what you are looking for:
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()
Is this what you are trying to accomplish?
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"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.