Objective-C 代码 (array.indexOfObjectPassingTest) 到 Swift

Objective-C code (array.indexOfObjectPassingTest) to Swift

如何在 Swift 中使用下面的 Objective-C 代码,我试过了,但出了点问题。

Objective-C:

NSUInteger index = [theArray indexOfObjectPassingTest:
            ^BOOL(NSDictionary *dict, NSUInteger idx, BOOL *stop)
            {
                return [[dict objectForKey:@"name"] isEqual:theValue];
            }
    ];

Swift(无效):

let index = theArray.indexOfObjectPassingTest { (var dict: NSDictionary, var ind: Int, var bool: Bool) -> Bool in
                return dict.objectForKey("name")?.isEqual("theValue")
            }

我猜你需要这个:

var index: UInt = theArray.indexOfObjectPassingTest({(dict: [NSObject: AnyObject], idx: UInt, stop: Bool) -> BOOL in    return dict.objectForKey("name").isEqual(theValue)

})

我玩过它并让它工作:

let theArray: NSArray = [["name": "theName"], ["name": "theStreet"], ["name": "theValue"]]

let index = theArray.indexOfObjectPassingTest { (dict, ind, bool) in return dict["name"] as? String == "theValue" }

if index == NSNotFound {
    print("not found")
} else {
    print(index)    // prints "2"
}

这可以进一步减少。正如@newacct 在评论中提到的, return 可以删除,因为闭包只是一行。此外,_ 可用于代替未使用的参数:

let index = theArray.indexOfObjectPassingTest { (dict, _, _) in dict["name"] as? String == "theValue" }

您可以完全去掉闭包中的参数列表并使用默认的 [=15=] 值。请注意,在这种情况下,三个参数组合为一个元组,因此元组的第一个值 dict 被引用为 [=17=].0:

let index = theArray.indexOfObjectPassingTest { [=12=].0["name"] as? String == "theValue" }

Swift 3:

考虑这个方法: public func index(where predicate: (Element) throws -> Bool) rethrows -> Int?

下面举例说明如何使用它:

let dict1 = ["name": "Foo"]
let dict2 = ["name": "Doh"]

let array = [dict1, dict2]


let index = array.index { (dictionary) -> Bool in
    return dictionary["name"] == "Doh"
}

这个returns值1。

希望对您有所帮助

我最终将其用于 Swift5 项目:

let index = self.info.indexOfObject(passingTest: { (obj:Any, ind:Int, stop:UnsafeMutablePointer<ObjCBool>) -> Bool in
        if let details = obj as? NSDictionary, let id = details["id"] as? Int
        {
           if (orderId == id)
           {
              stop.pointee = true
              return true
           }
        }
        return false;
     })

其中orderId是我要查找的对象的id值。