You can use reduce
and optionals, preventing usage of forced unwrapping, which can cause the app to crash if the string doesn't actually contain numbers.
Here's the code:
let array = string.componentsSeparatedByString(",")
let initial: Int? = .None
let max = array.reduce(initial) {
let num = $1.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).toInt()
return num > $0 ? num : $0
}
The first line splits the string into an array of strings - notice that there's no need of a cast, because the method already returns an array of strings.
The reduce
method is used by passing an optional integer as initial value, set to .None
(which is a synonym for nil
).
The closure passed to reduce
converts the current value into an integer using toInt()
, which returns an optional, to account for the string not convertible to a valid integer.
Next, the closure returns the converted number, if it's greater than the value calculated at the previous iteration (or than the initial value), otherwise it returns the value at the last iteration.
Note that comparing integers and nil is perfectly legit: any integer value is always greater than nil
(even a negative value).
This method works with a "normal" list of numbers:
let string = "1, 2, 3, 4, 5, 6, 7" // The result is 7
but also with lists having numbers and non-numbers:
let string = "1, 2, three, 4, 5, 6, seven" // the result is 6
and with lists containing no numbers:
let string = "one, two, three, three, four, five, six, seven" // the result is nil