Home > Back-end >  user generic function to determine the instance type in swift
user generic function to determine the instance type in swift

Time:11-30

I have three classes that conforms to same object type (protocol).

    class Bicycle: Vehicle {}
    class Car : Vehicle {}
    class Truck: Vehicle {}
    class Bus : Vehicle {}

I have an array that holds objects of the above classes like

let vehicle1 = Car()
let vehicle2 = Bicycle()
let vehicle3 = Truck()
let vehicle4 = Car()
let vehicle5 = Bus()

let listOfVehicles = [vehicle1, vehicle2, vehicle3, vehicle4, vehicle5]

Now I need an array which will tell me the index of the parameter that passed.

func getFirstIndex<T: Vehicle>(for targetObject: T) -> Int {
     guard let index = listOfVehicles.firstIndex(where: {  $0 is targetObject.Type }) 
     else { 
        return -1
     }
     return index
}

If I call getFirstIndex(for: vehicle3), I need to get 2 and

If I call getFirstIndex(for: vehicle4), I need to get 0, because vehicle4's type and vehicle1's type is same which is Car.

But I am getting compile-error "Type of expression is ambiguous without more context".

Does anyone have any clue.

CodePudding user response:

Just replace targetObject.Type with T

  • Related