Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String Array into Int Array Swift 2?

Tags:

[Xcode 7.1, iOS 9.1]

I have an array: var array: [String] = ["11", "43", "26", "11", "45", "40"]

I want to convert that (each index) into an Int so I can use it to countdown from a timer, respective of the index.

How can I convert a String array into an Int Array in Swift 2?

I've tried several links, none have worked and all of them have given me an error. Most of the code from the links is depreciated or hasn't been updated to swift 2, such as the toInt() method.

like image 516
Lukesivi Avatar asked Oct 26 '15 14:10

Lukesivi


People also ask

How to convert string array into integer array Swift?

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))! }

How do I convert a string to an array in Swift?

To convert a string to an array, we can use the Array() intializer syntax in Swift. Here is an example, that splits the following string into an array of individual characters. Similarly, we can also use the map() function to convert it. The map() function iterates each character in a string.

Can we convert array to set in Swift?

You don't have to reduce an array to get it into a set; just create the set with an array: let objectSet = Set(objects.

Are there arrays in Swift?

In Swift, each element in an array is associated with a number. The number is known as an array index. In the above example, we have created an array named languages . Here, we can see each array element is associated with the index number.


1 Answers

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] 
like image 50
vadian Avatar answered Sep 27 '22 20:09

vadian