Convert String Array into Int Array Swift 2?
Swift 4, 5:
The instant way if you want to convert string numbers into arrays of type int (in a particular case i've ever experienced):
let pinString = "123456"
let pin = pinString.map { Int(String($0))! }
And for your question is:
let pinArrayString = ["1","2","3","4","5","6"]
let pinArrayInt = pinArrayString.map { Int($0)! }
Swift 4, 5:
Use compactMap with cast to Int, solution without '!'.
let array = ["1","foo","0","bar","100"]
let arrayInt = array.compactMap { Int($0) }
print(arrayInt)
// [1, 0, 100]
Use the map
function
let array = ["11", "43", "26", "11", "45", "40"]
let intArray = array.map { Int($0)!} // [11, 43, 26, 11, 45, 40]
Within a class like UIViewController
use
let array = ["11", "43", "26", "11", "45", "40"]
var intArray = Array<Int>!
override func viewDidLoad() {
super.viewDidLoad()
intArray = array.map { Int($0)!} // [11, 43, 26, 11, 45, 40]
}
If the array contains different types you can use flatMap
(Swift 2) or compactMap
(Swift 4.1+) to consider only the items which can be converted to Int
let array = ["11", "43", "26", "Foo", "11", "45", "40"]
let intArray = array.compactMap { Int($0) } // [11, 43, 26, 11, 45, 40]