1
var array = [(Int, String)]()

I need the pairs in the array sorted in ascending order by the value of the Int.

array = [(2, "is"), (0, "Hello"), (1, "this"), (3, "Ben")]

I need this to return:

array = [(0, "Hello"), (1, "this"), (2, "is"), (3, "Ben")]

I think some variation of the following should work, but I can't figure out how to set it up.

array.sortInPlace()

2 Answers 2

6
let array = [(2, "is"), (0, "Hello"), (1, "this"), (3, "Ben")]
let sortedArray = array.sort { $0.0 < $1.0 }

print(sortedArray) // [(0, "Hello"), (1, "this"), (2, "is"), (3, "Ben")]

The .0 part represents the first object of the tuple.

See Matt's answer for the mutable version.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm not even joking when I say this answer (and question) changed my life. Tuples.
2

Like this:

var array = [(2, "is"), (0, "Hello"), (1, "this"), (3, "Ben")]
array.sortInPlace{$0.0 < $1.0}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.