Convert String Array into Int Array Swift 2?

后端 未结 4 2087
日久生厌
日久生厌 2021-01-01 14:37

[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

4条回答
  •  我在风中等你
    2021-01-01 15:17

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

提交回复
热议问题