zhuber
zhuber

Reputation: 5524

Assign value to Swift property

When should I assign value to properties in swift?

What is the difference between

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

and this

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

Actually its quite obvious when value is assigned on init() but when is value assigned when using 1st piece of code and which is the right way to do?

Upvotes: 4

Views: 3156

Answers (3)

Rob
Rob

Reputation: 437432

They're the same, but Apple suggests using the default property value pattern "if a property always takes the same initial value" for stylistic reasons. See the note in Default Property Values section of The Swift Programming Language: Initialization, which says:

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.

Upvotes: 4

Mark McCorkle
Mark McCorkle

Reputation: 9414

They should both be doing the same thing. The main difference for not initializing first would be if you wanted to assign the var as an optional and test for nil. Otherwise assigning the value would be the same.

var something:String?

Upvotes: 0

Antonio
Antonio

Reputation: 72750

You can use any of the 2. The difference is that if you have multiple initializer you might need to replicate the property initialization. Besides that it's just a matter of preference.

Upvotes: 0

Related Questions