2

I have a String array:

values = [textField1.text!, textField2.text!, textField3.text!, textField4.text!, textField5.text!]

and I want to convert it to an Int array. How do i do it in swift 2.0?

7
  • What if a text field does not contain a valid integer representation? Commented Jan 12, 2016 at 16:16
  • 1
    @SergiiZhevzhyk Just a note: the accepted answer in the duplicate (I agree, it's very close to a duplicate) also presents an un-safe version using forced unwrapping, much like flashspys original answer below. The best would naturally be if the linked post could update its answer with a safe method, but until then, I suggest this post is not closed as duplicate. Commented Jan 12, 2016 at 16:22
  • @dfri the first comment at the accepted answer already does that Commented Jan 12, 2016 at 16:44
  • @LeoDabus I saw you comment, but knowing how people sometimes use answers here on SO, it's quite easy to miss. I think the answer itself should be updated to be safe if it's to be marked as a duplicate for question touching the same subject. Note that in this case, the answer in that thread will most likely break a lot of "swift newcomers" code. vidian explicitly states that "but the given array in the question is doubtless an array of convertible numbers", so I'd say the linked answer is too narrow to be an answer to this one. Hence: vidians answer edited, or this is not a duplicate. Commented Jan 12, 2016 at 16:50
  • (generally, a good answer should be exhaustive on its own, without the implicit use of comments below it) Commented Jan 12, 2016 at 16:52

2 Answers 2

7

You can use the Swift map function:

var intArray = values.map({Int($0) ?? 0})
Sign up to request clarification or add additional context in comments.

3 Comments

This assumes that all the textFields are convertible to integers. There really should be some error checking. +1 anyway.
thats true. let myIntArrSafe = myStringArr.map { Int($0) ?? 0 } from @dfri is a very nice solution
With this solution, you cannot determine the difference between an invalid number and "0". It would be better to return an array of [String?] and let the caller deal with the nil values. i.e. let probablyNumbers = myStringArray.map{ Int($0) }
2

First of all, you should probably not initialize you string array with forced unwrappings of optional strings (what if one of the text fields .text property is nil? Runtime exception). You could do this in a safe way using the nil coalescing operator:

let myStringArr = [textField1.text ?? "0", textField2.text  ?? "0"]

Now, the same goes for type conversion: e.g. a string "foo" will return nil for attempted conversion Int("foo") (not, per se, conversion, but initialization of Int by String). Hence, given you've safely arrived at a string array (as per the code example above), you can, again, use the nil coalescing operator to ensure safe initializations of Int entries in your Int array:

let myStringArr = ["1", "foo", "4", "bar", "3.5"]

let myIntArrSafe = myStringArr.map { Int($0) ?? 0 }
print(myIntArrSafe)
/* [1, 0, 4, 0, 0] */

Another solution would be to extend String type by a safe integer conversion, returning 0 in case of Int by String initialization failure.

extension String {
    var integerValue: Int { return Int(self) ?? 0 }
}

let myStringArr = ["1", "foo", "4", "bar", "3.5"]

let myIntArrSafe = myStringArr.map { $0.integerValue }
print(myIntArrSafe)
/* [1, 0, 4, 0, 0] */

6 Comments

You could also use flatMap to take any nil values out of the Int array.
@MrBeardsley indeed; you will then however loose any reference as to which text fields produced nil entries, as well as which Integer values are associated to which text fields (as resulting Int array is (given nils) truncated)
@dfri that's true, the true is also that if the result is 0, you don't know why (it could be the result of "foo" string, or "0" string. so, everything depends on your specific needs. I prefer an [Int?] as a result. I prefer Int?(str: String) etc.
@user3441734 The benefits of getting 0 entries is that at least you know which string entries that failed Int initialization. With a flatMap, you loose this information as the resulting array is truncated, and you cannot know how it has been truncated (hence: loss of element-to-element reference to original array)
@dfri i didn't mention flatMap ... I prefer [Int?] In that case i can enumerate and next flatMap to [(index, integerValue)], where index is index to orig. [String]
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.