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 ts 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 ints. 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

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -