rorama
rorama

Reputation: 11

Setter/Getter in protocol in swift

branchID is set to be a getter BUT I am able to set the value. What is the use of specifying it to be a setter/ getter?

    protocol Bank {
    var name: String {get set}
    var branchID: Int {get}
}

struct Person: Bank {enter code here
    var name: String = "ABC Bank"
    var branchID: Int = 123
}

let person = Person()
person.name
person.branchID

Upvotes: 1

Views: 607

Answers (2)

vadian
vadian

Reputation: 285069

First of all the code doesn't use the protocol.

If an object adopts a protocol it must implement the protocol requirements. Your code creates an object Person with all capabilities of Person

var person = Person()

and you can change branchID

person.branchID = 13

However if you cast person to Bank

var bank = person as Bank
bank.branchID = 13

you will get the error

Cannot assign to property: 'branchID' is a get-only property

The same error occurs if you declare a function which tries to update all objects which conform to Bank

func updateID(item : Bank)
{
    item.branchID = 12
}

Upvotes: 1

Fawcus
Fawcus

Reputation: 1

branchID in Person is a new object,You can certainly change its value. when you write 'Bank. branchID',you can't set its value

Upvotes: 0

Related Questions