Tuesday, June 30, 2026
HomeiOS Developmentios - consumer generic operate to find out the occasion sort in...

ios – consumer generic operate to find out the occasion sort in swift

[ad_1]

I’ve three courses that conforms to similar object sort (protocol).

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

I’ve an array that holds objects of the above courses like

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

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

Now I would like an array which is able to inform me the index of the parameter that handed.

func getFirstIndex<T: Car>(for targetObject: T) -> Int {
     guard let index = listOfVehicles.firstIndex(the place: {  $0 is targetObject.Sort }) 
     else { 
        return -1
     }
     return index
}

If I name getFirstIndex(for: vehicle3), I must get 2 and

If I name getFirstIndex(for: vehicle4), I must get 0,
as a result of vehicle4’s sort and vehicle1’s sort is similar which is Automotive.

However I get compile-error “Sort of expression is ambiguous with out extra context”.

Does anybody have any clue.

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments