Objective-C code (array.indexOfObjectPassingTest) to Swift

▼魔方 西西 提交于 2019-12-19 10:23:11

问题


How can I use the Objective-C code below in Swift, I tried but something is wrong.

Objective-C:

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

Swift (Doesn't work):

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

回答1:


I played with it and got this to work:

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"
}

This can be further reduced. As @newacct mentioned in the comment, the return can be dropped since the closure is only a single line. Also, _ can be used in place of the parameters that aren't being used:

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

You can get rid of the parameter list in the closure entirely and use the default $0 value. Note in that case, the three parameters are combined as a tuple, so the first value of the tuple dict is referenced as $0.0:

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



回答2:


Swift 3:

Consider this method: public func index(where predicate: (Element) throws -> Bool) rethrows -> Int?

The following gives you an example how to use it:

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

let array = [dict1, dict2]


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

This returns the value 1.

Hope that helps




回答3:


Guess you need this:

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

})



回答4:


I ended up using this for a Swift5 project:

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;
     })

Where orderId is id value of the object I wanted to find.



来源:https://stackoverflow.com/questions/31909686/objective-c-code-array-indexofobjectpassingtest-to-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!