How to declare/ initialize a property?

Sorry for the very beginner question. But, this is something that I can't wrap my head around.
In what cases should I declare or initialize a property like this:

struct Person {
    var name: String             
    var name = ""                 
    var name = String()    

    let name: String         
}

var name: String probably is the “default” way. Initial value will have to be set in the initializer.

Options 2 & 3 are the same thing. Used when you have a reasonable default value.

Normally let is not needed inside structs (but quite common in classes!), because mutability of structs is controlled on the outer layer anyway:

let p: Person = ...
p.name = ... // error

But, sometimes you need to make properties read-only if setting a property may break invariant of the struct:

struct Square {
    var size: CGFloat
    var area: CGFloat
    init(size: CGFloat) {
        self.size = size
        self.area = size * size // invariant
    }
}
var sq = Square(size: 10) // 10-100, ok
sq = Square(size: 20) // 20-400, ok
sq.size = 30 // 30-400, bug

Using let fixes this:

struct Square {
    let size: CGFloat
    let area: CGFloat
    init(size: CGFloat) {
        self.size = size
        self.area = size * size // invariant
    }
}
var sq = Square(size: 10) // 10-100, ok
sq = Square(size: 20) // 20-400, ok
sq.size = 30 // compile-time error
sq = Square(size: 30) // 30-900, ok

But often that’s a premature optimization. I’d recommend first trying to implement this using computed properties, and use let only if profiler shows performance issues:

struct Square {
    var size: CGFloat
    var area: CGFloat { size * size }
    init(size: CGFloat) {
        self.size = size
    }
}
var sq = Square(size: 10) // 10-100, ok
sq = Square(size: 20) // 20-400, ok
sq.size = 30 // 30-900, ok
5 Likes

Thanks for the comprehensive answer. It really helped.

Terms of Service

Privacy Policy

Cookie Policy