NSIndexSet.enumerateIndexesUsingBlock using Swift Closure

1.8k views Asked by At

I'm writing a method to copy data from a table view to the paste board but if any rows are selected it should specifically only copy the data from the selected rows so I need to iterate over the index set ...

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

I'm having a bit of a trouble with interpreting the method signature to how I should write the closure code. The error message I get isn't particularly clear either (Cannot invoke 'enumerateIndexesUsingBlock' with an argument list of type '((_, _) -> Int)'). Can somebody help me out here?

EDIT:

Working method:

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

There are 1 answers

1
kishikawa katsumi On BEST ANSWER

In a multiple line of closure, probably you should write the parameter list and return value explicitly. You can write like below:

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