Objective-C代码(array.indexOfObjectPassingTest)到Swift
如何在Swift中使用Objective-C代码,我试过,但是有些错误。
How can I use the Objective-C code below in Swift, I tried but something is wrong.
Objective-C: / p>
Objective-C:
NSUInteger index = [theArray indexOfObjectPassingTest:
^BOOL(NSDictionary *dict, NSUInteger idx, BOOL *stop)
{
return [[dict objectForKey:@"name"] isEqual:theValue];
}
];
Swift(无效):
$ b
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")
}
我使用它并让它工作:
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
。此外, _
可用于替换未使用的参数:
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" }
你可以完全摆脱闭包中的参数列表,默认的 $ 0
值。注意,在这种情况下,三个参数组合为一个元组,因此元组 dict
的第一个值被引用为 $ 0.0
:
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" }