2

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]?

5 Answers 5

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

Optionals are implicitly initialized to nil, = .None is not needed.
I change let initial: Int? = .None to let initial: int! = .None cause I have to get the string, so return "\(max)" will have some optional string, but int! will be OK. Anyway, thanks for your answer!
@KaKa: Making it an implicitly unwrapped doesn't necessarily mean you will get a non nil result - If I were in you, I'd limit usage of them to really necessary cases, favoring normal optionals in all other cases.
@Antonio ,Great! I got what you mean! Looks like I haven't got the truly usage of optionals, I prefer to use ! than ?, looks like I have to learn swift deeply
2

you can map the array

let string = "1,2,3,4,5,6"
let numArray = string.componentsSeparatedByString(",").map {$0.toInt()!}

2 Comments

Got an error "AnyObject doesn't have a member named toInt()"
If you know that this AnyObject is a string, cast it to String with as! String
1
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].

Comments

0

In Swift 2.0,

let string = "1,2,3,4,5,6"
let numArray = string.componentsSeparatedByString(",").map{ Int($0)! }

Comments

0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.