Reputation: 559
My question is simple,
let string = "1,2,3,4,5,6"
As I want to find the max value in the string, and I want to use the method in this way, so I need to do this:
let array = string.componentsSeparatedByString(",") as [AnyObject]
let numArray = array as! [Int]
let maxNum = numArray.reduce(Int.min, combine: {max($0,$1)})
But, there will be an error in "array as! [Int]"
fatal error: array cannot be bridged from Objective-C
And if it's
let numArray = array as! [String]
It will be ok but we cannot use the reduce method.
So, how to convert the array with string to [Int]?
Upvotes: 2
Views: 2262
Reputation: 135
In Swift 4.0:
let string = "1,2,3,4,5,6"
let stringArray = string.split(separator: ",").map(String.init)
let intArray = stringArray.flatMap(Int.init)
intArray.max()
Upvotes: 0
Reputation: 3809
In Swift 2.0,
let string = "1,2,3,4,5,6"
let numArray = string.componentsSeparatedByString(",").map{ Int($0)! }
Upvotes: 0
Reputation: 72760
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
Upvotes: 2
Reputation: 2190
let string = "1,2,3,4,5,6"
func toInt(str: String) -> Int {
return str.toInt()!
}
let numArray = map(string.componentsSeparatedByString(",") as [String], toInt)
Then, numArray
is [1, 2, 3, 4, 5, 6]
.
Upvotes: 1
Reputation: 285079
you can map the array
let string = "1,2,3,4,5,6"
let numArray = string.componentsSeparatedByString(",").map {$0.toInt()!}
Upvotes: 2