无法分配给 Swift 中“Y"中的“X" [英] Cannot assign to 'X' in 'Y' in Swift
问题描述
我有一本带有 Structs
的字典.当我遍历 dictionary
时,我试图分配 struct
的值.Swift 告诉我 cannotassign to 'isRunning' in 'blockStatus'
.我无法在文档中找到任何关于 dictionaries
或 structs
的特定不变性的内容.
就在操场上:
I have a dictionary with Structs
in it. I am trying to assign the values of the struct
when I loop through the dictionary
. Swift is telling me cannot assign to 'isRunning' in 'blockStatus'
. I haven't been able to find anything in the docs on this particular immutability of dictionaries
or structs
.
Straight from the playground:
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
如果我将 struct
更改为 class
,这确实有效.
This does work if I change the struct
to a class
.
我猜这与复制结构和总是引用类有关?
所以即使它正在复制它..为什么我不能改变它?它会给我带来错误的结果,但您可以更改常量的成员,而不是常量本身.例如你可以这样做:
So even if it is copying it.. Why can't I change it? It would net me the wrong result but you can change members of constants just not the constant themselves. For example you can do this:
class A {
var b = 5
}
let a = A()
a.b = 6
推荐答案
你的猜测是对的.
通过访问 blockStatus
,您正在创建它的副本,在这种情况下,它是一个常量副本(迭代器始终是常量).
By accessing blockStatus
, you are creating a copy of it, in this case, it's a constant copy (iterators are always constant).
这类似于以下内容:
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.
值类型是一种在分配给变量或常量或传递给函数时被复制的类型.[...] 所有结构和枚举在 Swift 中都是值类型
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.
但是,如果您需要在特定方法中修改结构或枚举的属性,您可以选择改变该方法的行为.然后,该方法可以在方法内改变(即更改)其属性,并且在方法结束时,它所做的任何更改都会写回原始结构.该方法还可以为其隐式 self 属性分配一个全新的实例,该新实例将在该方法结束时替换现有实例.
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.
您可以通过在该方法的 func 关键字之前放置 mutating 关键字来选择加入此行为:
You can opt in to this behavior by placing the mutating keyword before the func keyword for that method:
这篇关于无法分配给 Swift 中“Y"中的“X"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!