Convert String Array into Int Array Swift 2?
Asked Answered
A

5

24

[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.

Aplite answered 26/10, 2015 at 14:19 Comment(0)
R
74

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]
Restate answered 26/10, 2015 at 14:23 Comment(6)
the map function it is ok but you should not recommend forcing unwrap text array.map{ Int($0) ?? 0 } would be a better (safer) choiceLimekiln
You're right, but the given array in the question is doubtless an array of convertible numbers. It's up to the developer to take care of the type whether optional testing is really needed.Restate
Sorry for the wait! My TableViewController is giving me an error says that I can't convert my array on type "TableViewController". Is there an exception for the TableViewController class? @Restate instance member 'array' cannot be used on type TableViewControllerAplite
You have to put the line to map the array in a function for example viewDidLoad(). Declare the variable on class level as implicit unwrapped optionalRestate
Thanks. This works when the objects are already in the array, therefore answering my question. My issue is that I'm querying from Parse, and THEN i'd like to convert the String values into Ints. Any suggestions? Thanks for your time in any case!Aplite
You can use the line to map the array everywhere for example after retrieving the data from ParseRestate
B
12

Swift 4, 5:

Use compactMap with cast to Int, solution without '!'.

'compactMap' filters nil values and applies a transformation.

let array = ["1","foo","0","bar","100"]
let arrayInt = array.compactMap { Int($0) }

print(arrayInt)
// [1, 0, 100]
Bankrupt answered 20/2, 2020 at 15:58 Comment(0)
B
4

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)! }
Brim answered 25/11, 2019 at 7:41 Comment(1)
You saved from doing unnecessary conversion from array of string to array of Int from a String(Originally).Dissymmetry
S
1

i suggest a little bit different approach

let stringarr = ["1","foo","0","bar","100"]
let res = stringarr.map{ Int($0) }.enumerate().flatMap { (i,j) -> (Int,String,Int)? in
    guard let value = j else {
        return nil
    }
    return (i, stringarr[i],value)
}
// now i have an access to (index in orig [String], String, Int) without any optionals and / or default values
print(res)
// [(0, "1", 1), (2, "0", 0), (4, "100", 100)]
Selfgratification answered 12/1, 2016 at 18:23 Comment(0)
P
0

A slightly different example

let digitNames = [0: "Zero", 1: "One", 2:"Two", 3: "Three",
                  4:"Four",5:"Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", 10:"Ten"

]

let numbers = [16,58,510]
let strings = numbers.map { (number) -> String in
    var number = number
    var output = ""
    repeat {
        output = digitNames[number % 10]! + output
        number /= 10
        
    } while number > 0
            return (output)
}

print(strings)


// strings is inferred to be of type [String]

// its value is ["OneSix", "FiveEight", "FiveOneZero"]
Pruinose answered 14/11, 2022 at 11:31 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Disestablish

© 2022 - 2024 — McMap. All rights reserved.