繁体   English   中英

如何快速实例化具有不同类型的同一通用协议的多个实例?

[英]How to instantiate multiple instances of the same generic protocol with different types in swift?

我有一个通用协议P,并且我希望其他B类具有不同类型的该协议的不同实例。 我想模拟以下行为:

protocol P<T> {
    func getAll() -> [T]
}

class B {
    var foo1: P<Int>

    var foo2: P<String>
}

如何快速完成此任务?

您无法使用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]
}

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()

这是您要完成的工作吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM