LAST CHANCE: Save 50% on all my Swift books and bundles! >>

SOLVED: Day 13: Need help solving an error

Forums > 100 Days of SwiftUI

After working through Paul's explanation of a protocol (and after creating a new struct that implements the protocol he created at the beginning of the video), my playground threw me an error that I'm not sure how to fix. When I called the commute method while using the Bicycle() struct as an arguement, I get an error that states "Cannot convert value of type 'Bicycle' to expected argument type 'Car'."

How do I fix this error?

protocol Vehicle {
    func estimateTime(for distance: Int) -> Int
    func travel(distance: Int)
}

struct Car: Vehicle {

    func estimateTime(for distance: Int) -> Int {
        distance / 50
    }

    func travel(distance: Int) {
        print("I'm driving \(distance)km.")
    }

    func openSunroof() {
        print("It's a nice day.")
    }
}

// Creating a new struct to reexamine how the protocol works
struct Bicycle: Vehicle {
    func estimateTime(for distance: Int) -> Int {
        distance / 10
    }

    func travel(distance: Int) {
        print("I'm cycling \(distance)km.")
    }
}

func commute(distance: Int, using vehicle: Car) {
    if vehicle.estimateTime(for: distance) > 100 {
        print("That's too slow! I'll try a different vehicle.")
    } else {
        vehicle.travel(distance: distance)
    }
}

let car = Car()
commute(distance: 100, using: car)
// Error gets thrown when I use 'bike' below
let bike = Bicycle()
commute(distance: 10, using: bike)

3      

Your function expects to receive a type 'Car' in the call, but you pass it a type 'Bicycle'.

func commute(distance: Int, using vehicle: Car) {

You need to have the function expect the more generic type 'Vehicle' in the call, instead.

func commute(distance: Int, using vehicle: Vehicle) {

Both types 'Car' and 'Bicycle' are defined as and conform to the protocol 'Vehicle'.

4      

This was perfectly explained. Thank you! I'll work on going back over my code and doing the rubber ducky method to see where my errors are coming from.

3      

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until July 28th.

Click to save your free spot now

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.