import Cocoa struct BlockStatus{ var isRunning = false var timeGapForNextRun = UInt32(0) var currentInterval = UInt32(0) } var statuses = ["block1":BlockStatus(),"block2":BlockStatus()] for (block,blockStatus) in statuses{ blockStatus.isRunning = true } cannot assign to 'isRunning' in 'blockStatus' blockStatus.isRunning = true
如果我将结构更改为一个类,这样做会起作用。
我猜测它与复制结构和总是引用类的事实有关系?
编辑:所以即使它是复制它..为什么我不能改变它?它会净我错误的结果,但你可以改变常量的成员,而不是常数本身。例如,您可以这样做:
class A { var b = 5 } let a = A() a.b = 6
通过访问blockStatus,您正在创建它的副本,在这种情况下,它是一个常量副本(迭代器总是不变的)。
这类似于以下内容:
var numbers = [1,2,3] for i in numbers { i = 10 //cannot assign here }
参考文献:
In the example above,index is a constant whose value is automatically set at the start of each iteration of the loop.
A value type is a type that is copied when it is assigned to a variable or constant,or when it is passed to a function. […] All structures and enumerations are value types in Swift
Structures and enumerations are value types. By default,the properties of a value type cannot be modified from within its instance methods.
However,if you need to modify the properties of your structure or enumeration within a particular method,you can opt in to mutating behavior for that method. The method can then mutate (that is,change) its properties from within the method,and any changes that it makes are written back to the original structure when the method ends. The method can also assign a completely new instance to its implicit self property,and this new instance will replace the existing one when the method ends.
You can opt in to this behavior by placing the mutating keyword before the func keyword for that method: