在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()
}
在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()
}
在这两种情况下,都是对这个数组进行操作:
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"
]
我会给你这个答案:
["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"]
在Swift 2.0版本中,你应该能够执行
last.flatMap(Int.init)
,但由于某些原因它无法正常工作。即使像
["1", "2"].flatMap(Int.init)
这样的操作也会导致我的playground崩溃。看起来像是一个bug。