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

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)

2      

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'.

3      

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.

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!

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.