czekhoff czekhoff - 9 days ago 5
iOS Question

How compare two objects in Swift?

How can I compare two objects? Below is my code

enum Object {
case empty
case value(Int)
}

func == (first: Object, second: Object) -> Bool {
return first == second
}

var objects = [Object.empty, Object.value(2), Object.value(5), Object.empty, Object.value(3)]
var integers: [Int] = []

for obj in objects {
for index in 0...10 {
if obj == Object.value(index) {
integers.append(index)
} else {
integers.append(0)
}
}
}


But this doesn't work. The func runs many times. What is wrong?

enter image description here

Answer

Try something like this...

func ==(first: Object, second: Object) -> Bool {
  switch(first, second) {
      case(.value(let a), .value(let b)) where a == b: return true
      case(.empty, .empty): return true
      default: return false
  }
}

Then in the for loop...

for obj in objects {
  for index in 0...10 {
    if obj == Object.value(index) {
      integers.append(index)
    } else {
      integers.append(0)
    }
  }
Comments