4

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'

Palimondo
  • 7,281
  • 4
  • 39
  • 58
Frederick C. Lee
  • 9,019
  • 17
  • 64
  • 105

2 Answers2

11

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 }
}
Boomerange
  • 616
  • 1
  • 10
  • 18
drewag
  • 93,393
  • 28
  • 139
  • 128
  • 2
    A more pertinent sort would sort by the first element of the tuple first, then sort by the second in case the first one is equal. `myStringArray!.sort { $0.0 == $1.0 ? $0.1 < $1.1 : $0.0 < $1.0 }` – noliv Jun 15 '14 at 23:05
6

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.

Frederick C. Lee
  • 9,019
  • 17
  • 64
  • 105