How to compare generic objects in Swift? -
consider following simplified snippet:
class foo<t: equatable> { var x: t init(_ x: t, _ y: t) { self.x = x if (x == y) { // } } }
i class work kinds of t
s somehow comparable. ideally compare identities if t object , directly compare else conforms equatable
.
code above doesn't work array
example. if change equatable
anyobject
, ==
===
doesn't work int
s. how solve problem? thought creating own protocol couldn't figure out how implement types conform equatable
.
edit:
didn't know work on mac because on linux , when try compile
foo<[int]>([1, 2], [1, 2])
i following error:
error: type '[int]' not conform protocol 'equatable' foo<[int]>([1, 2], [1, 2]) ^
a simple solution add initializer arrays of equatable
elements.
class foo<t: equatable> { init(_ x: t, _ y: t) { if (x == y) { print("initialization equal equatable types.") } } init(_ x: [t], _ y: [t]) { if (x == y) { print("initialization equal arrays of equatable types.") } } } let = foo<int>(1, 1) /* initialization equal equatable types. */ let b = foo<int>([1, 2, 3], [1, 2, 3]) /* initialization equal arrays of equatable types. */
Comments
Post a Comment