arrays - Swift indexOf 不一致的行为

标签 arrays swift indexof nsobject equatable

我似乎面临着与 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: NSObjectObj: 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)

他们在这里

enter image description here

您可以在下面阅读每个结果后的原因

结果#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 get nil as result

结果#2

array.indexOf(array.last!) // 2

Again isEqual is used. However here you are passing to indexOf 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 the value property is used.

结果#4

array.filter { $0 == object } // [{NSObject, value 5}]

Again the == operator is used and then the value property is used to check for equality.

关于arrays - Swift indexOf 不一致的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38741522/

相关文章:

c - 为什么会有不同的答案?

javascript - JSON 使用 node.js 循环多维数组

swift - Restkit,如何在没有对象映射的情况下访问响应对象

ios - 如何检查 Swift 中的 3 个字符串是否相等?

javascript - 在 Javascript 数组的前半部分查找元素

Java:空白索引问题

Javascript如何使用包装器将节点附加到其正确的索引中

python - 如何使用 numpy 配对 (x,y) 对

PHP 唯一数组值?

IOS/swift : Pass Object in tableview to detail view controller