【发布时间】:2022-01-03 21:14:47
【问题描述】:
多个类方法是否可以访问和修改在类构造函数中设置的单个 inout 参数?例如这样的:
class X {
var mySwitch: Bool
init(mySwitch: inout Bool) {
self.mySwitch = mySwitch
}
func updateSwitch() {
self.mySwitch.toggle() // this should toggle the external Boolean value that was originally passed into the init
}
}
// usage
var myBool: Bool = false
let x = X(mySwitch: &myBool)
x.updateSwitch()
print(myBool) // this should read 'true'
【问题讨论】:
-
明确禁止将捕获更改为像这样的值类型,特别是为了防止这种情况。允许这样做会使它们进入共享可变状态,这完全违背了值类型的目的。
-
你能扩展
explicitly forbidden, specifically to prevent this吗?即使值类型可以具有共享状态(通过使用 & 将它们显式传递给 inout 参数),将其限制在单个方法的范围内是否有一些优势? -
inout就像在将值传递给调用时复制了该值,并在调用结束时复制了(覆盖原始值)。不会发生别名(对同一可变状态的多次引用),因此是可以接受的。 -
知道了,谢谢@Alexander。
标签: swift sprite-kit