swift convert Range<Int> to [Int]

IosArraysSwiftIntRange

Ios Problem Overview


how to convert Range to Array

I tried:

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

get error Range<Int> is not convertible to [Int]

I also tried:

let intArray:[Int] = [min...max]

and

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

they don't work either.

Ios Solutions


Solution 1 - Ios

You need to create an Array<Int> using the Range<Int> rather than casting it.

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

Solution 2 - Ios

Put the Range in the init.

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

Solution 3 - Ios

I figured it out:

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

Giving credit to someone else.

Solution 4 - Ios

do:

let intArray = Array(min...max)

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

Solution 5 - Ios

Use map

let min = 50
let max = 100
let intArray = (min...max).map{$0}

Solution 6 - Ios

Interesting that you cannot (at least, with Swift 3 and Xcode 8) use Range<Int> object directly:

let range: Range<Int> = 1...10
let array: [Int] = Array(range)  // Error: "doesn't conform to expected type 'Sequence'"

Therefore, as it was mentioned earlier, you need to manually "unwrap" you range like:

let array: [Int] = Array(range.lowerBound...range.upperBound)

I.e., you can use literal only.

Solution 7 - Ios

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

Solution 8 - Ios

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhaithamView Question on Stackoverflow
Solution 1 - IosDavid SkrundzView Answer on Stackoverflow
Solution 2 - IosMr BeardsleyView Answer on Stackoverflow
Solution 3 - IoshaithamView Answer on Stackoverflow
Solution 4 - Iosad121View Answer on Stackoverflow
Solution 5 - IosvadianView Answer on Stackoverflow
Solution 6 - IosdevforfuView Answer on Stackoverflow
Solution 7 - IoskillobattView Answer on Stackoverflow
Solution 8 - IosEdisonView Answer on Stackoverflow