Frederick C. Lee
Frederick C. Lee

Reputation: 9493

How to sort an Array of Tuples?

How do you implement (or create) an array sort of a list of tuples?
The following was gleaned from my code.

Essentially I created an array of tuples and populated it via for loop; after which I tried to sort it.

var myStringArray: (String,Int)[]? = nil
...

myStringArray += (kind,number)
...

myStringArray.sort{$0 > $1}

This is what Xcode gave me before I could build:

test.swift:57:9: '(String, Int)[]?' does not have a member named 'sort'

Upvotes: 4

Views: 9293

Answers (2)

drewag
drewag

Reputation: 94723

You have two problems. First, myStringArray is an Optional, you must "unwrap" it before you can call methods on it. Second, there is no > operator for tuples, you must do the comparison yourself

if let myStringArray = myStringArray {
    myStringArray.sort { $0.0 == $1.0 ? $0.1 > $1.1 : $0.0 > $1.0 }
}

Upvotes: 12

Frederick C. Lee
Frederick C. Lee

Reputation: 9493

Actually, what I was looking for, is the tuple with the largest integer value:

var myStringArray: (String,Int)[]? = nil
...
println("myStringArray: \(myStringArray)\n")
myStringArray!.sort {$0.1 > $1.1}
println("myStringArray: \(myStringArray)\n")
...

Original:

myStringArray: [(One, 1), (Square, 1), (Square, 4), (Square, 9), (Square, 16), (Square, 25), (Prime, 2), (Prime, 3), (Prime, 5), (Prime, 7), (Prime, 11), (Prime, 13), (Fibonacci, 1), (Fibonacci, 1), (Fibonacci, 2), (Fibonacci, 3), (Fibonacci, 5), (Fibonacci, 8)]

Sorted:

myStringArray: [(Square, 25), (Square, 16), (Prime, 13), (Prime, 11), (Square, 9), (Fibonacci, 8), (Prime, 7), (Prime, 5), (Fibonacci, 5), (Square, 4), (Prime, 3), (Fibonacci, 3), (Prime, 2), (Fibonacci, 2), (One, 1), (Square, 1), (Fibonacci, 1), (Fibonacci, 1)]

...so it's the "square" having the largest integer: 25.

Upvotes: 6

Related Questions