swift 有可能有一个 ViewController
吗?从 xib 初始化的类有一个属性也是 UIViewController
的子类并符合某些协议(protocol)?
protocol SomeProtocol {
// Some methods
}
class ViewController: UIViewController {
// contentView is initialized from xib
@IBOutlet weak var contentView: UIView!
// I'd like to declare anotherViewController both conforms to 'SomeProtocol'
// and a subclass of UIViewController
var anotherViewController: UIViewController!
...
}
当我声明ViewController
作为通用类,说 class ViewController<T: UIViewController, SomeProtocol>
,我得到一个错误:
"Variable in a generic class cannot be presented in Objective-C"
那么如果不能使用泛型类怎么实现呢?
最佳答案
如果我误解了你的问题,请原谅我,但我认为你想要做的是声明一个继承自 UIViewController 并符合 SomeProtocol 的新类型,如下所示:
protocol SomeProtocol { }
class VCWithSomeProtocol: UIViewController, SomeProtocol {
}
class ViewController: UIViewController {
var anotherViewController: VCWithSomeProtocol!
}
关于swift - 如何使用符合某些协议(protocol)的属性声明一个 swift 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26626114/