NSIndexSet.enumerateIndexesUsingBlock 使用 Swift 闭包

NSIndexSet.enumerateIndexesUsingBlock using Swift Closure

我正在编写一种将数据从 table 视图复制到粘贴板的方法,但是如果选择了任何行,它应该专门只复制所选行中的数据,因此我需要遍历索引集 ...

func createExportText(fromArrayController:NSArrayController) -> String
{
    var indexSet = fromArrayController.selectionIndexes;
    /* None were selected, so process them all! */
    if (indexSet.count == 0)
    {
        indexSet = NSIndexSet(indexesInRange: NSMakeRange(0, fromArrayController.arrangedObjects.count));
    }

    var rows = "";
    indexSet.enumerateIndexesUsingBlock
    {
        // What code goes here?
    }

    return rows;
}

我在将方法签名解释为应该如何编写闭包代码时遇到了一些麻烦。我收到的错误消息也不是特别清楚 (Cannot invoke 'enumerateIndexesUsingBlock' with an argument list of type '((_, _) -> Int)')。有人可以帮我吗?

编辑:

工作方式:

func createExportText(fromArrayController:NSArrayController) -> String
{
    var rows = "";
    var indexSet = fromArrayController.selectionIndexes;
    let objects = (fromArrayController.arrangedObjects as! NSArray);

    /* No rows were selected, so process them all! */
    if (indexSet.count == 0)
    {
        indexSet = NSIndexSet(indexesInRange: NSMakeRange(0, objects.count));
    }

    indexSet.enumerateIndexesUsingBlock
    {
        (i, stop) -> Void in

        let obj:AnyObject = objects[i];
        let str = obj.valueForKey("string") as! String;
        rows += "\(str)";
        if (i < indexSet.lastIndex) { rows += "\n"; }
    }

    return rows;
}

在多行闭包中,您可能应该显式地编写参数列表和 return 值。 你可以这样写:

indexSet.enumerateIndexesUsingBlock { (index, stop) -> Void in
    println(index)
}