In Swift 2:
import Foundation
let myArray = ["Step 6", "Step 12", "Step 10"]
extension String {
func extractIntFromEnd() -> Int? {
return self.componentsSeparatedByString(" ").last.flatMap{Int($0)}
}
}
let ans = myArray.sort {
(first, second) in
first.extractIntFromEnd() < second.extractIntFromEnd()
}
In Swift 1:
let myArray = ["Step 6", "Step 12", "Step 10"]
extension String {
func extractIntFromEnd() -> Int? {
return self.componentsSeparatedByString(" ").last.flatMap{$0.toInt()}
}
}
let ans = myArray.sorted {
(first, second) in
first.extractIntFromEnd() < second.extractIntFromEnd()
}
In both, this array:
let myArray = [
"Step 6" ,
"Step 12",
"Step 5" ,
"Step 14",
"Step 4" ,
"Step 11",
"Step 16",
"Step 9" ,
"Step 3" ,
"Step 13",
"Step 8" ,
"Step 2" ,
"Step 10",
"Step 7" ,
"Step 1" ,
"Step 15"
]
Will give you this answer:
["Step 1", "Step 2", "Step 3", "Step 4", "Step 5", "Step 6", "Step 7", "Step 8", "Step 9", "Step 10", "Step 11", "Step 12", "Step 13", "Step 14", "Step 15", "Step 16"]
(In the Swift 2.0 version, you should be able to do last.flatMap(Int.init), but it's not working for me for some reason. Even something like ["1", "2"].flatMap(Int.init) is crashing my playground. Looks like a bug.)