Convert string array to integer array in Swift
To convert a given array of strings into an array of integer values in Swift, you can use Array compactMap() method.
For example, if strArray is the given string array, and we would, like to convert this to an integer array, use the following code snippet.
</>
Copy
strArray.compactMap { Int($0) }
The function returns an integer array.
Examples
1. Convert an array of string to an array of integers
In this example, we will take an array of string values strArray, and convert this into an array of integer values intArray.
main.swift
</>
Copy
let strArray = ["123", "456", "789"]
let intArray = strArray.compactMap { Int($0) }
print("String array : \(strArray)")
print("Integer array : \(intArray)")
Output
Conclusion
In this Swift Tutorial, we have seen how to convert a given array of strings into an array of integers using compactMap() method of an Array class instance.