@user3815344's answer works, however you can simplify it by using minElement
and maxElement
to retrieve the minimum and maximum values. For example:
let arr = ["55a", "95a", "66", "25", "88b", "#"]
let numbers: [Int] = arr.reduce([]) {
if let num = "".join($1.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)).toInt() {
return $0 + [num]
}
return $0
}
minElement(numbers) // 25
maxElement(numbers) // 95
Updated for Swift 2: toInt
has been replaced by a failable initialiser on Int
that takes a String
and minElement
and maxElement
have been replaced by protocol extensions:
let arr = ["55a", "95a", "66", "25", "88b", "#"]
let numbers: [Int] = arr.reduce([]) {
if let num = Int("".join($1.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet))) {
return $0 + [num]
}
return $0
}
let min: Int? = numbers.minElement() // 25
let max: Int? = numbers.maxElement() // 95
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…