【问题标题】:Advanced Swift2 - Implementing Protocols in Class Vs Implementing Protocols in StructAdvanced Swift2 - 在类中实现协议与在结构中实现协议
【发布时间】:2015-08-15 12:03:56
【问题描述】:

// 协议

Protocol Movable {
  mutating func moveTo(p : CGPoint) 
}

虽然在类中实现协议是语法

Class Car : Movable {
 func moveTo(p : CGPoint) {...} 
}
Struct Shape : Movable {
 mutating func moveTo(p : CGPoint) {...} 
}

现在为什么必须在 struct 中插入“变异”,它在下面做什么。

【问题讨论】:

    标签: struct protocols swift2 ios9


    【解决方案1】:

    因为默认情况下结构被假定为不可变,而类实例被假定为可变。因此,您不需要标记修改类实例的函数,但必须标记修改结构的方法。假设你写了let myShape = Shape()。编译器需要知道它不能让你调用myShape.moveTo(...)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-25
      • 2017-03-19
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多