senty senty - 6 months ago 14
iOS Question

Array 'contains()' check is failing to detect rounded value

I have

Double
values which I am using
floor()
to round 0 to 1, and converting other double values to
Integer
. Then, I am using
contains()
to check if the value exists and if not, append them in array. Here is the snippet:

let radius = center.distanceFromLocation(location) / 1000
let section = floor(radius) == 0 ? 1 : Int(radius)

if !self.myArray.contains(Int(radius)) {
self.myArray.append(section)
}


The problem is, it's appending different values in
myArray
for '1' and '1 rounded from 0'.

Here is some debugs:

(lldb) po myArray
▿ 3 elements
- [0] : 1
- [1] : 1 { ... }
- [2] : 11 // it's working fine for other numbers

(lldb) po myArray[0]
1

(lldb) po myArray[1]
1

(lldb) po myArray[2]
11


(lldb) p myArray[0]
(Int) $R11 = 1

(lldb) p myArray[1]
(Int) $R10 = 1

Answer

You are checking !self.myArray.contains(Int(radius)) which is wrong in your case.

Lets say the array already contains a 1 and you know are wondering wether to insert 0.3. section becomes 1, but you check wether or not Int(radius) = 0 is contained already which it is not. Then you add the section (1) again.

Your code should be

if !self.myArray.contains(section) {
    self.myArray.append(section)
}

Or alternatively use a Set which ensures every value is contained at most once.