我使用的是Xcode 9.4.1和iOS 11.4.1上的SWIFT4.1。
我有几个协议,像这样:
protocol Bla {
// some stuff
}
protocol Gorp {
// some other stuff
}我有一些符合这两个协议的结构,比如:
typealias MyType = Bla & Gorp
struct Hello: MyType {
var ID: Int
var name: String
}
struct Goodbye: MyType {
var percentage: Double
var hairbrush: String
}然后我有一个论点,theType,它既符合Bla & Gorp,又符合Bla&Gorp。在这个例子中,我只是打印一个描述--就像这样:
func doSomething<T: MyType>(_ theType: T.Type) {
// some stuff
print("Got called... \(theType)")
}而且,我可以调用这个函数来传递两个结构类型(Hello和告别)中的每一个,如下所示:
doSomething(Hello.self)
doSomething(Goodbye.self)这很好,我得到了如下输出,就像预期的那样:
Got called... Hello
Got called... Goodbye然而,我真正想要做的是迭代其中的一堆,而不是单独调用它们。
这种方式给出了一个错误“注意:期望类型为‘(T.Type)’的参数列表”:
for thingy in [Hello.self, Goodbye.self] {
doSomething(thingy)
}如果我添加了一个!MyType.Type或as!MyType,我也有同样的错误。我也试过这样做:
for thingy in [Hello.self as MyType.Type, Goodbye.self as MyType.Type] {
doSomething(thingy)
}与其他错误相同。
我也尝试过没有类型的。
如果我开始输入,自动完成程序会显示doSomething正在等待一个(Bla & Gorp).Protocol类型的参数。所以,我也试过这个:
for thingy in [Hello.self, Goodbye.self] as! [(Bla & Gorp).Protocol] {
doSomething(thingy)
}在这种情况下,我得到了这样的信息:
In argument type '(Bla & Gorp).Protocol', 'Bla & Gorp' does not conform to expected type 'Bla'还尝试了这种类型的东西,这会导致错误,“不能用‘(DoSomething)’类型的参数列表调用‘MyType.Type’”:
struct AnyBlaGorp {
let blaGorp: MyType.Type
init<T: MyType>(_ theType: T.Type) {
self.blaGorp = theType
}
}
for thingy in [AnyBlaGorp(Hello.self), AnyBlaGorp(Goodbye.self)] {
doSomething(thingy.blaGorp)
}对神奇的正确语法的指针将是非常感谢的。:)
发布于 2018-08-06 01:52:28
您可以使doSomething方法非泛型,并接受MyType.Type。只有当您的协议没有Self或关联类型时,才能这样做。
func doSomething(_ theType: MyType.Type) {
// some stuff
print("Got called... \(theType)")
}接下来,将数组强制转换为[MyType.Type]。
for thingy in [Hello.self, Goodbye.self] as [MyType.Type] {
doSomething(thingy)
}这利用了这样一个事实,即如果A.self从/符合B继承,那么A可以转换为B类型。
https://stackoverflow.com/questions/51699601
复制相似问题