【问题标题】:Structure instance property value [duplicate]结构实例属性值 [重复]
【发布时间】:2016-12-04 15:41:59
【问题描述】:

我可以使用点表示法更新类实例的属性值但是它不适用于结构。

示例如下:

struct Resolution {
    var width = 0

}

class VideoMode {
  var interlaced = false
 }


let someResolution = Resolution()
let someVideoMode = VideoMode()

类:

someVideoMode.interlaced // false
someVideoMode.interlaced = true //true
someVideoMode.interlaced // now true 

对于结构:

 someResolution.width // 0
 someResolution.width  = 200 // throws an error says : someResolution is constant 

问题是:

someResolution 和 someVideoMode 都是常量。 我可以更改类实例的属性值而不会出错,而不是说 someVideoMode 是常量。但是 我无法更改 struct 的属性值。它会抛出错误,说 someResolution 是常量

为什么?

谢谢!

【问题讨论】:

  • 检查valueOfStructInstance定义不是let,因为这段代码编译没有任何错误

标签: swift


【解决方案1】:

structs 是值类型,而classes 是引用。

虽然您可以设置常量引用类型的属性,但您不能更改引用本身。

let someVideoMode = VideoMode()
someVideoMode = VideoMode()

会导致错误。

您可以在the documentation you actually got this sample from找到详细说明。

【讨论】:

  • 将 let 更改为 var 解决了问题,但在类实例中为什么它不抛出错误?它也被放在那里。
  • 更新答案。
  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2023-01-08
  • 2011-10-26
  • 1970-01-01
  • 1970-01-01
  • 2020-12-27
  • 1970-01-01
  • 2019-08-26
  • 1970-01-01
相关资源
最近更新 更多