UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Question: {get} and {get set} in protocols

Forums > 100 Days of SwiftUI

@boat  

In the tutorial of protocols https://www.hackingwithswift.com/quick-start/beginners/how-to-create-and-use-protocols

Paul said:

As well as methods, you can also write protocols to describe properties that must exist on conforming types. To do this, write var, then a property name, then list whether it should be readable and/or writeable.

For example, we could specify that all types that conform Vehicle must specify how many seats they have and how many passengers they currently have, like this:

protocol Vehicle {
    var name: String { get }
    var currentPassengers: Int { get set }
    func estimateTime(for distance: Int) -> Int
    func travel(distance: Int)
}

My question:

1, Can't we use let name : String ? Does it have to be var in protocol properties ?

2, both are var, it seems both can be rewritten and keeping changing, in my understanding , this means set , no ? what is the different between the {get} and {get set} when it's a variable ?

Thanks

Boat

2      

hi,

you use var name: String { get } because some structs or classes that conform to Vehicle may choose to implement the name as a computed property. (the same is true for { get set } properties.)

hope that helps,

DMG

added after the post: a struct or class that conforms to Vehicle may, in fact, implement the name property with a let.

2      

Hi @boat

protocols defines what name has to be in the struct or class that it attached to.

If the has { get } then it can be let or var, however if it a { get set } then has to a var only.

The advantage is that if someone uses a protocol on a struct or class then those names have to be there.

if you had a struct

struct SomeData {
    let id: String
    let title: String
}

You could do this for a list

List(someData, id: \.id) { data in
  Text(data.title)
}

However if you add the protocol of Identifiable this requires that a property name of id (which can be a let or var)is there so the List know the key \.id is guaranteed to be there so you can remove it

List(someData) { data in
  Text(data.title)
}

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.