我似乎面临着与 Swift 的 indexOf
不一致的行为功能。
有两个indexOf
Swift 中的函数:
1.第一个取Equatable
作为参数:array.indexOf(obj)
2. 第二个将匹配的闭包作为参数:array.indexOf{$0 == obj}
我有一个NSObject
==
的子类定义了运算符,即它符合 Equatable
因此,我假设这两个函数的工作原理完全相同(示例中带有闭包)。
但是,1st
方法的行为不一致,特别是它返回 nil
当使用对象调用时,数组中不存在该对象的实例。
为了说明问题,我提供了带有注释的示例代码:
class EqObj: NSObject {
let value: Int
init(value: Int) {
self.value = value
}
}
func ==(lhs: EqObj, rhs: EqObj) -> Bool{
return lhs.value == rhs.value
}
var array = [Obj(value: 1), Obj(value: 3), Obj(value: 5)]
var object = Obj(value: 5)
// returns nil, should return 2 - incorrect
array.indexOf(object) // Instance is not present
// returns 2, correct
array.indexOf(array.last!) // Instance is present
// returns 2, correct
array.indexOf{$0 == object} // Instance is not present, predicate
// returns non-empty array, correct
array.filter{$0 == object} // Instance is not present, predicate
此问题只能通过 NSObject
重现子类。当我改变Obj: NSObject
至Obj: Equatable
方法indexOf()
完全按照预期工作,即返回 2
.
问题是这是否可以被视为错误?
我的假设是array.indexOf(object)
调用isEqual
方法NSObject
而不是我重载的==
运算符。
我的解决方案:
我用array.indexOf{$0 == object}
最佳答案
首先,根据这个定义,我得到了不同的结果
class Obj: NSObject {
let value: Int
init(value:Int) {
self.value = value
}
}
func ==(lhs: Obj, rhs: Obj) -> Bool{
return lhs.value == rhs.value
}
var array = [Obj(value: 1), Obj(value: 3), Obj(value: 5)]
var object = Obj(value: 5)
他们在这里
您可以在下面阅读每个结果后的原因
结果#1
array.indexOf(object) // nil
In this case the isEqual method is used, so you are just comparing memory address. And since the
object
var references an object NOT inside the array, you getnil
as result
结果#2
array.indexOf(array.last!) // 2
Again
isEqual
is used. However here you are passing toindexOf
the reference to the last object in the array so it works.
结果#3
array.indexOf { $0 == object } // 2
Here you are explicitly using the
==
operator you defined so thevalue
property is used.
结果#4
array.filter { $0 == object } // [{NSObject, value 5}]
Again the
==
operator is used and then thevalue
property is used to check for equality.
关于arrays - Swift indexOf 不一致的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38741522/