var myArray: [[String]] =
[
["1", "picture1.png", "John", "Smith"],
["2", "picture2.png", "Mike", "Rutherford"],
]
How to sort myArray on first item ? second item ? ascending ? descending ?
Many Thanks
I would suggest you create a struct or class to package this related data together:
struct Person {
let id: Int
let picture: String // This should probably be a URL, NSImage or UIImage
let firstName: String
let lastName: String
}
And then define your instances with the correct types (e.g. the id is an Int, not a String representation of an Int.
let people = [
Person(
id: 1,
picture: "picture1.png",
firstName: "John",
lastName: "Smith"
),
Person(
id: 2,
picture: "picture2.png",
firstName: "Mike",
lastName: "Rutherford"
),
]
From there, you can sort it any which way you please:
people.sorted{ $0.id < $1.id }
people.sorted{ $0.id > $1.id }
people.sorted{ $0.picture < $1.picture }
people.sorted{ $0.picture > $1.picture }
people.sorted{ $0.firstName < $1.firstName }
people.sorted{ $0.firstName > $1.firstName }
people.sorted{ $0.lastName < $1.lastName }
people.sorted{ $0.lastName > $1.lastName }
Notice, that index ranged is not checked, what could lead to a fatal error at runtime. Check Alexanders comment! :)
var myArray: [[String]] =
[
["1", "picture1.png", "John", "Smith"],
["2", "picture2.png", "Mike", "Rutherford"],
]
func sort<T: Comparable>(ArrayOfArrays: [[T]], sortingIndex: Int, sortFunc: (T, T) -> Bool)) -> [[T]] {
return ArrayOfArrays.sorted {sortFunc($0[sortingIndex], $1[sortingIndex])}
}
}
print(sort(ArrayOfArrays: myArray, sortingIndex: 0, sortFunc: <))
//[["1", "picture1.png", "John", "Smith"], ["2", "picture2.png", "Mike", "Rutherford"]]
print(sort(ArrayOfArrays: myArray, sortingIndex: 0, sortFunc: >))
//[["2", "picture2.png", "Mike", "Rutherford"], ["1", "picture1.png", "John", "Smith"]]
Swift's Array has a built-in sort function. Just call it.
myArray[0].sort { $0.compare($1, options: .numeric) == .orderedAscending }
myArray[1].sort { $0.compare($1, options: .numeric) == .orderedDescending }
To sort the arrays using numeric string comparison (e.g. where "2" < "10") of the item at a particular index:
let index = 1 // sort by second entry
myArray.sort { $0[index].compare($1[index], options: .numeric) == .orderedAscending }
If you don't need numeric comparisons (e.g. where "10" < "2"):
myArray.sort { $0[index] < $1[index] }
As others point out, though, you really should be using arrays of custom struct or class rather than representing your objects as mere array of strings.
structorclassthat represent the info in that array with properties like index (I guess that's what 1 or 2 mean), pictureName, Name, FamilyName rather than using an array of strings.