WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Computed property question

Forums > 100 Days of SwiftUI

Hi,

For computed properties, we are given this example:

struct Employee {
    let name: String
    var vacationAllocated = 14
    var vacationTaken = 0

    var vacationRemaining: Int {
        vacationAllocated - vacationTaken
    }
}

Then we are advised if we want to "write to" the code, we should use a getter and a setter like this;

struct Employee {
    let name: String
    var vacationAllocated = 14
    var vacationTaken = 0

    var vacationRemaining: Int {
        get {
            vacationAllocated - vacationTaken
        }
        set {
            vacationAllocated = vacationTaken + newValue
        }
}

}

First, I don't understand what "write to" the code means. Secondly, I'm not sure why we need to use a getter and a setter. It seems like we can just change the initial variables in the first code to get the same information.

Will appreciate it if someone will help clarify.

Thank you, Arthur

   

Let me use a different example.

struct Programmer {
    let name: String
    var distanceFromWall = 30
    var screenDistanceFromWall = 20
    var distanceFromScreen: Int {
        distanceFromWall - screenDistanceFromWall
    }
}

You might create a programmer object and see that, by default, the programmer is a distance of 10 from her computer's screen. If you change her distance from the wall to 40, she'll be a distance of 20 from her screen. You compute this value each time you want to know the distance.

But WHAT IF you wanted to specify the distance between the programmer and her screen? One way would be to move the monitor, or reseat the programmer. However, with a setter, you can give the desired value to the computed property. Then you let the computed property either (1) move the programmer or (2) move the monitor. That's your business to decide!

In this case you are "writing to" the computed property.

struct Programmer {
    let name: String
    var distanceFromWall = 30
    var screenDistanceFromWall = 20
    var distanceFromScreen: Int {
        get {
            distanceFromWall - screenDistanceFromWall // no change here
        }
        set {
            // easier to move the programmer, than move the screen! 
            // Here you change the programmer's distance to the wall
            // so that the programmer is now "newValue" distance from the monitor.
            distanceFromWall = screenDistanceFromWall + newValue // moving the programmer!
        }       
    }
}

You are correct however. In the inital example, you can just change the vacation variables. But this is not the concept that @twostraws was teaching in this lesson.

1      

Setting a computed property can also be useful when you want to keep the stored properties as private but still want to give the user the means to change them.

struct Account {
    let id = UUID()
    private(set) var balance: Double
    private var transactions: [Double] = []

    init(initialBalance: Double) {
        balance = initialBalance
    }

    var latestTransaction: Double {
        get { transactions.last ?? 0 }
        set { transactions.append(newValue) }
    }
}

var acct = Account(initialBalance: 10_000_000)
acct.latestTransaction = -10_000

In this case, we don't want the user to have direct access to the transactions array (because we don't want them doing account.transactions[2] or whatever), so we use a computed property to control access to the private property.

1      

Thank you @Obelix & @roosterboy. This clarifies things a lot for me.

   

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.