如何在Swift中使用indicesOfObjectsPassingTest:

时间:2014-06-04 15:41:58

标签: ios closures swift

indexOfObjectsPassingTest的声明:在Swift中看起来像这样,

func indexesOfObjectsPassingTest(predicate: ((AnyObject!, Int, CMutablePointer<ObjCBool>) -> Bool)!) -> NSIndexSet!

我已经尝试过各种各样的排列方式来实现这一点,但我很难过,尤其是你如何处理这篇文章,CMutablePointer<ObjCBool>) -> Bool)!。我发现它很混乱,当我第一次学习objective-c中的块时,你如何从声明转换为实际使用方法,而Swift的语法至少是令人困惑的。

3 个答案:

答案 0 :(得分:7)

此代码在我的游乐场工作;)希望它有所帮助

额外功能定义

import Cocoa

let list = [2, 3, 4, 5, 6, 7, 8]

func test (object: AnyObject!, index: Int, stop: CMutablePointer<ObjCBool>) -> Bool
{
    let number = object as Int
    return (number % 2 == 0) //for even numbers
}

let result: NSIndexSet = (list as NSArray).indexesOfObjectsPassingTest(test)

println("\(result.lastIndex)") //prints "6" (because 8%2=0)

直列封

我将上面的示例转换为内联闭包(在Swift-eBook中描述)。参数列表和返回类型由术语in分隔。

import Cocoa

let list = [2, 3, 4, 5, 6, 7, 8]

let result: NSIndexSet = (list as NSArray).indexesOfObjectsPassingTest({
(object: AnyObject!, index: Int, stop: CMutablePointer<ObjCBool>) -> Bool in
    let number = object as Int
    return (number % 2 == 0) //for even numbers
})

println("\(result.lastIndex)") //prints "6" (because 8%2=0)

答案 1 :(得分:4)

似乎CMutablePointer最近更改为UnsafeMutablePointer。

这个对我有用:

let indices = myArray.indexesOfObjectsPassingTest({
    (obj: AnyObject!, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Bool in
    var didPass = false
    //determine if obj passes test, if it does set didPass = true
    return didPass
})

答案 2 :(得分:0)

块语法在Swift中被一个闭包替换,这里是predicate参数。

所以你可以这样做:

var array = NSArray(array: [1, 2, 3, 4, 5])

var indexSet = array.indexesOfObjectsPassingTest({ (val: AnyObject!, index: Int, stop: CMutablePointer<ObjCBool>) -> Bool in return index > 2 })

indexSet.count

在方法之外,它可能如下所示:

var closure = {(val: AnyObject!, index: Int, stop: CMutablePointer<ObjCBool>) -> Bool? in
    /* Do Something */
}

希望这有帮助。