SLN SLN - 1 year ago 37
Swift Question

Unable to change protocol conformance of an object

In the code, the

Wheeled
and
Vehicle
are protocols, the
Bike
class conforms to both of the protocols

protocol Wheeled {
var numberOfWheels: Int { get }
}

protocol Vehicle {
var maker: String { get }
var owner: String {get set}
var ownerKid: String { get }
}


class Bike: Vehicle, Wheeled {
let numberOfWheels: Int = 0
var ownerKid: String = "Junior"

var maker: String {
return "Ford"
}

var owner: String {
get {
return "Bob"
}
set {
ownerKid = "\(newValue) Junior"
}
}
}

let bike: Bike = Bike()

var theBike: Vehicle = bike // #1
var theBike: Wheeled = bike // #2 error: invalid redeclaration of 'theBike'


When I check the properties of
theBike
, in #1,
theBike
object only has the properties conform to the
Vehicle
protocol; while in #2
theBike
object only has the properties conform to the
Wheeled
properties

Therefore, I feel
theBike
in #1 and #2 is different, why it tells me that invalid redeclaration?

Question: how should I change the protocol conformance of an object? Or is it allowed to change the conformance of an object?

Appreciate your time and help.

Answer
  • You cannot declare a variable (i.e. with the same name) twice.
  • If you need to access the properties of another protocol, use if let ... as? ... to recast.

Example:

if let theBike = theBike as? Wheeled  {
    print(theBike.numberOfWheels)
}