【问题标题】:Swift Typealias for Class and Protocol类和协议的 Swift 类型别名
【发布时间】:2017-08-06 02:52:57
【问题描述】:

我有一个变量必须是UIView,它也实现了协议MTMathKeyboard

我试过了,

var keyboard: (UIView & MTMathKeyboard)
var keyboard: UIView<MTMathKeyboard>

实现协议的非泛型类实例的语法是什么?

【问题讨论】:

标签: swift types


【解决方案1】:

我认为你应该走这条路:

protocol MTMathKeyboard: class {

}

class YourClass<MTMathKeyboard where T:UIView> {
    var keyboard: T!
}

【讨论】:

    【解决方案2】:

    您可以使用协议组合并扩展 UIView 以满足占位符协议:

    protocol UIViewClass {}
    extension UIView:UIViewClass {}
    
    
    var keyboard :  UIViewClass & MTMathKeyboard
    

    【讨论】:

      【解决方案3】:

      在 Swift 4 中,您可以使用:

      let keyboard: UIView & MTMathKeyboard
      

      【讨论】:

      • 很有帮助,这个功能叫什么名字?我一直在寻找文档。
      【解决方案4】:
      typealias KeyboardView = UIView & MTMathKeyboard
      
      protocol MTMathKeyboard: class {
      }
      
      private func updateController(with view: KeyboardView) {
              someView = view
      }
      

      【讨论】:

      • 一个很好的例子说明为什么坚持代码格式化指南是有帮助的:someView = keyboard 这里一个名为 keyboard 的对象不存在,但它是一个类型名称。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-16
      • 2015-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多