Swift generics and extensions need to workout -
this question has answer here:
- array extension remove object value 13 answers
im learning swift currently. while learning i'm stuck generics. im solving 1 simple problem -> return index of specified element in array
import uikit extension array { func indexofletter<t:equatable>(item:t) -> int { var = 0 (index, value) in enumerate(self) { if value == item { return } i++ } return -1; } } var arrayofitems = ["a","b"] arrayofitems.indexofletter("a") in code i'm getting error
can not compare 2 operands using == operator of type t.
the answer problem becomes more clear if use letter other t our generic identifier.
change method signature use letter u. , error message:

binary operator '==' cannot applied operands of type 't' , 'u'
this same error, it's made more clear using different letter. array type generic generic identifier t type.
when use u unmasks real problem.
the equatable protocol requires our type defines == comparisons itself. compare 2 u's long u's type equatable. equatable protocol not ensure can compare u t using ==.
this stack overflow answer can provide insight on difficulties of using equatable protocol generics.
Comments
Post a Comment