gpt4 book ai didi

ios - 为 Swift 属性赋值

转载 作者:可可西里 更新时间:2023-11-01 01:06:34 24 4
gpt4 key购买 nike

什么时候应该在 swift 中为属性赋值?

有什么区别

class Thing {
var something:String = "Cool Thing"
}

还有这个

class Thing {
var something:String
init(){
something = "Cool Thing"
}
}

实际上,在 init() 上赋值时很明显,但是在使用第一段代码时何时赋值,哪种方法是正确的?

最佳答案

它们是相同的,但出于风格原因,Apple 建议使用默认属性值模式“如果属性始终采用相同的初始值”。请参阅 The Swift Programming Language: Initialization默认属性值部分中的注释,它说:

Default Property Values

You can set the initial value of a stored property from within an initializer, as shown above. Alternatively, specify a default property value as part of the property’s declaration. You specify a default property value by assigning an initial value to the property when it is defined.

NOTE: If a property always takes the same initial value, provide a default value rather than setting a value within an initializer. The end result is the same, but the default value ties the property’s initialization more closely to its declaration. It makes for shorter, clearer initializers and enables you to infer the type of the property from its default value. The default value also makes it easier for you to take advantage of default initializers and initializer inheritance, as described later in this chapter.

关于ios - 为 Swift 属性赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26805816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com