[英]Can I declare a type that is a specific class conforming to a protocol in Swift?
If I have the following code: 如果我有以下代码:
class MyClass {
...
}
protocol MyProtocol {
...
}
Is it possible to declare a type that accepts a class or subclass of MyClass
conforming to MyProtocol
? 是否可以声明一个接受符合
MyProtocol
的MyClass
类或子类的MyProtocol
?
eg in pseudo code: 例如在伪代码中:
var thing: MyClass & MyProtocol = ...
The naive approach works (ie specify the type first and then use it in the variable declaration): 天真的方法有效(即首先指定类型然后在变量声明中使用它):
class MCImplementingMP: MyClass, MyProtocol {
}
var thing: MCImplementingMP = ...
Nope, it was possible in Objective-C but not possible in Swift. 不,在Objective-C中它是可能的,但在Swift中是不可能的。 All solutions that I know looks like hacks and require lot of runtime type checking.
我所知道的所有解决方案看起来都很糟糕,需要大量的运行时类型检查。 So I came out with my own - declare a wrapper type which can act like needed class or protocol depending on circumstances:
所以我自己出来 - 声明一个包装类型,根据具体情况,它可以像所需的类或协议一样:
class MyClass {}
protocol MyProtocol: class {}
class Wrapper {
var instance: AnyObject
init?(instance: MyClass) {
guard instance is MyProtocol else { return nil }
self.instance = instance
}
init?(instance: MyProtocol) {
guard instance is MyClass else { return nil }
self.instance = instance
}
var instanceAsMyClass: MyClass {
return instance as! MyClass
}
var instanceAsMyProtocol: MyProtocol {
return instance as! MyProtocol
}
}
You may want to change property names but idea is clear. 您可能想要更改属性名称,但想法很清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.