@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
3
solved How to get minimum & maximum value in a NSString/String array?