SLN
SLN

Reputation: 5082

Compiler didn't fire an error when creating an object from a Protocol

Here is the code example from the resource I've reading

protocol Vehicle {
    var weight: Int { get }
    var name: String { get set }
}

protocol WheeledVehicle: Vehicle {
    var numberOfWheels: Int { get }
    var wheelSize: Double { get set }
}


class Bike: WheeledVehicle{
    var weight: Int = 30
    var name: String = "kukulus"
    var numberOfWheels: Int = 2
    var wheelSize: Double = 16.2}

var bike: Bike = Bike()

bike.numberOfWheels = 16

var wheeledBike: WheeledVehicle = bike // *** There will be an error, in fact not.

For the last line (marked with ***)

Question 1 The book I read claimed that here will be an error fired by the compiler that "Cannot assign to numberOfWheels!", however, it's not. Is the book wrong?

Question 2 var wheeledBike: WheeledVehicle = bike where WheeledVehicle is a protocol, isn't it like an abstract class that protocol cannot instantiate an object? if so, why didn't the compiler give me an error warning?

Update: If adds the following code, there will be an error notice

wheeledBike.numberOfWheels = 4

The book is not wrong, the above line will introduce an error, not the line marked with ***

Thanks a lot for your time and help

Upvotes: 0

Views: 27

Answers (1)

ogres
ogres

Reputation: 3690

In the following code you are creating a Bike object, which has var numberOfWheels property, var means you can change it and thats why you are able to change the value of numberOfWheels.

var bike: Bike = Bike()
bike.numberOfWheels = 16

The following line works because Bike class conforms to protocol WheeledVehicle, thus bike can be casted as wheeledBike. You are NOT creating a new object, but you are just assigning it to a new variable.

var wheeledBike: WheeledVehicle = bike

If you tried following code, it would fail, because wheeledBike is type of WheeledVehicle which has var numberOfWheels: Int { **get** }, here get means that by protocol, you are only able to retrieve this value, but you are NOT allowed to set/change it.

wheeledBike.numberOfWheels = 16

Upvotes: 1

Related Questions