Ios 数组';包含();检查未检测到舍入值
我有Ios 数组';包含();检查未检测到舍入值,ios,arrays,swift,append,contains,Ios,Arrays,Swift,Append,Contains,我有Double值,我正在使用floor()将0四舍五入为1,并将其他双精度值转换为Integer。然后,我使用contains()检查该值是否存在,如果不存在,则将其追加到数组中。以下是片段: let radius = center.distanceFromLocation(location) / 1000 let section = floor(radius) == 0 ? 1 : Int(radius) if !self.myArray.contains(Int(radius)) {
Double
值,我正在使用floor()
将0四舍五入为1,并将其他双精度值转换为Integer
。然后,我使用contains()
检查该值是否存在,如果不存在,则将其追加到数组中。以下是片段:
let radius = center.distanceFromLocation(location) / 1000
let section = floor(radius) == 0 ? 1 : Int(radius)
if !self.myArray.contains(Int(radius)) {
self.myArray.append(section)
}
问题是,它在myArray
中为“1”和“1”添加了不同的值,从0取整
以下是一些调试:
(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
是的,因为以Int(半径)为例,Int(1)和Int(0.45)是不同的。
您应该尝试检查myArray是否包含section,而不是Int(radius),因为它可能会导致您遇到不正确的行为。您正在检查
!self.myArray.contains(Int(radius))
在您的情况下是错误的
假设数组已经包含一个1
,您知道是否需要插入0.3
<代码>部分变为1
,但您要检查Int(radius)
=0
是否已经包含,但它没有包含。然后再次添加部分
(1
)
你的代码应该是
if !self.myArray.contains(section) {
self.myArray.append(section)
}
或者使用
集合
,确保每个值最多包含一次。请提供实际值进行测试。它类似于:“0,1,11”。11.工作正常。。但是,“1”和“从0取整的1”的行为类似于2个不同的值,即使它们都是1