swift convert Range to [Int]

前端 未结 8 593
感动是毒
感动是毒 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:54

    do:

    let intArray = Array(min...max)
    

    This should work because Array has an initializer taking a SequenceType and Range conforms to SequenceType.

    0 讨论(0)
  • 2021-02-03 16:57

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

    let range: CountableRange<Int> = -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)
    }
    
    0 讨论(0)
  • 2021-02-03 17:01

    I figured it out:

    let intArray = [Int](min...max)
    

    Giving credit to someone else.

    0 讨论(0)
  • 2021-02-03 17:01

    Use map

    let min = 50
    let max = 100
    let intArray = (min...max).map{$0}
    
    0 讨论(0)
  • 2021-02-03 17:04

    You can implement ClosedRange & Range instance intervals with reduce() in functions like this.

    func sumClosedRange(_ n: ClosedRange<Int>) -> Int {
        return n.reduce(0, +)
    }
    sumClosedRange(1...10) // 55
    


    func sumRange(_ n: Range<Int>) -> Int {
        return n.reduce(0, +)
    }
    sumRange(1..<11) // 55
    
    0 讨论(0)
  • You need to create an Array<Int> using the Range<Int> rather than casting it.

    let intArray: [Int] = Array(min...max)
    
    0 讨论(0)
提交回复
热议问题