Swift:如何在不调用didSet函数的情况下更改属性的值 [英] Swift: how to change a property's value without calling its didSet function
问题描述
如何在Swift中设置属性的值,而无需在初始化上下文之外调用didSet()
函数?下面的代码是在类的noside()
函数
How can you set a property's value in Swift, without calling its didSet()
function outside of an initialization context? The code below was a failed experiment to achieve this within the classes' noside()
function
class Test
{
var toggle : Bool = 0
var hoodwink : Int = 0 {
didSet(hoodwink)
{
toggle = !toggle
}
}
// failed attempt to set without a side effect
func noside(newValue : Int)
{
hoodwink = newValue
println("hoodwink: \(hoodwink) state: \(toggle)")
}
func withside(newValue : Int)
{
self.hoodwink = newValue
println("hoodwink: \(hoodwink) state: \(toggle)")
}
}
在Objective-C中使用自动合成的属性是很简单的:
It is quite trivial to do in Objective-C with auto-synthesized properties:
有副作用(如果出现在二传手中):
With side effect (if present in setter):
self.hoodwink = newValue;
没有副作用:
_hoodwink = newValue;
推荐答案
您在Objective-C中为避免副作用"所做的操作正在访问属性的后备存储-它的实例变量,默认情况下带有下划线前缀(您可以使用@synthesize
指令更改此变量).
What you do in Objective-C to "avoid side effects" is accessing the backing store of the property - its instance variable, which is prefixed with underscore by default (you can change this using the @synthesize
directive).
但是,看来Swift语言设计人员特别注意使不可能访问属性的后备变量:根据书,
However, it looks like Swift language designers took specific care to make it impossible to access the backing variables for properties: according to the book,
如果您有使用Objective-C的经验,您可能知道它提供了两种将值和引用存储为类实例的一部分的方法.除了属性之外,您还可以将实例变量用作存储在属性中的值的后备存储.
If you have experience with Objective-C, you may know that it provides two ways to store values and references as part of a class instance. In addition to properties, you can use instance variables as a backing store for the values stored in a property.
Swift将这些概念统一为一个属性声明. Swift属性没有相应的实例变量,并且不能直接访问该属性的后备存储. (强调是我的)
Swift unifies these concepts into a single property declaration. A Swift property does not have a corresponding instance variable, and the backing store for a property is not accessed directly. (emphasis is mine)
当然,这仅适用于使用常规语言".意味着,与使用反射相反:它可能会提供一种绕过此限制的方法,但会降低可读性.
Of course this applies only to using the "regular language" means, as opposed to using reflection: it might provide a way around this restriction, at the expense of readability.
这篇关于Swift:如何在不调用didSet函数的情况下更改属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!