Convert String Array into Int Array Swift 2?

試著忘記壹切 提交于 2019-12-30 03:50:06

问题


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


回答1:


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]



回答2:


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)]



回答3:


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


来源:https://stackoverflow.com/questions/33348056/convert-string-array-into-int-array-swift-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!