swift - 如何使用符合某些协议(protocol)的属性声明一个 swift 类

标签 swift

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/

相关文章:

ios - 枚举 : Count and list all cases (from outside! )

ios - 使用相同背景图像的具有多个场景的 View Controller (UIViewController) Storyboard

swift - 如何修复 Swift 对 double 不准确的调试描述?

swift - 工具栏正在删除我在NavigationView中的后退按钮

ios - 发生了什么让我的键盘变成了一个酒吧

Swift JSON to Dictionary<String : Any>. Then cast "Any"as NSMutableArray

ios - 将一个 VNCoreMLFeatureValueObservation 结果(3D Double Array)转换为多个 UIImage

iOS 地理定位,当初始化和声明一起发生时代码工作不同

ios - 调试苹果支付消息支付请求无效: <private>

ios - 从文本字段上的日期选择器设置当前日期