swift convert Range to [Int]

前端 未结 8 596
感动是毒
感动是毒 2021-02-03 16:51

how to convert Range to Array

I tried:

let min = 50
let max = 100
let intArray:[Int] = (min...max)

get error Range is

8条回答
  •  攒了一身酷
    2021-02-03 16:57

    Since Swift 3/Xcode 8 there is a CountableRange type, which can be handy:

    let range: CountableRange = -10..<10
    let array = Array(range)
    print(array)
    // prints: 
    // [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    It can be used directly in for-in loops:

    for i in range {
        print(i)
    }
    

提交回复
热议问题