结构 – 无法在Swift中的“Y”中分配给“X”

前端之家收集整理的这篇文章主要介绍了结构 – 无法在Swift中的“Y”中分配给“X”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个带有Structs的字典。当我循环通过字典时,我试图分配struct的值。 Swift告诉我不能在’blockStatus’中分配给’isRunning’。我没有能够在文档中找到任何关于字典或结构体的这种特殊的不变性。直接从操场:
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
}

参考文献:

Control Flow

In the example above,index is a constant whose value is automatically set at the start of each iteration of the loop.

Classes and Structures

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

Methods

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:

原文链接:https://www.f2er.com/swift/320611.html

猜你在找的Swift相关文章