Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple member extraction in closure arguments

Tags:

swift

tuples

Considering this array of tuple :

var tupleArray = [(String, Int)]()
tupleArray.append(("bonjour", 2))
tupleArray.append(("Allo", 1))
tupleArray.sort { (t1 , t2) -> Bool in
    let (_, n1) = t1
    let (_, n2) = t2
    return n1 < n2
}

I would like to make the closure shorter by doing something like this :

tupleArray.sort { ((_, n1) , (_, n2)) -> Bool in
    n1 < n2
}

First: is it possible?
Second: if possible what is the syntaxe?

Thanks

like image 260
Vincent Bernier Avatar asked Apr 25 '15 14:04

Vincent Bernier


1 Answers

Well, you can use short closure syntax:

tupleArray.sort { $0.1 < $1.1 }

See the official guide about short closure syntax, the .1 is just tuple index access.

like image 56
Benjamin Gruenbaum Avatar answered Jan 03 '23 17:01

Benjamin Gruenbaum