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?
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?
You can use the Swift map function:
var intArray = values.map({Int($0) ?? 0})
let myIntArrSafe = myStringArr.map { Int($0) ?? 0 } from @dfri is a very nice solution[String?] and let the caller deal with the nil values. i.e. let probablyNumbers = myStringArray.map{ Int($0) }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] */
flatMap to take any nil values out of the Int array.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)