简体   繁体   English

swift将Range <Int>转换为[Int]

[英]swift convert Range<Int> to [Int]

how to convert Range to Array 如何将Range转换为Array

I tried: 我试过了:

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

get error Range<Int> is not convertible to [Int] 获取错误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. 他们也不工作。

您需要创建一个Array<Int>使用Range<Int> ,而不是荷兰国际集团它。

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

将Range放在init中。

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

I figured it out: 我想到了:

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

Giving credit to someone else. 给予别人信任。

do: 做:

let intArray = Array(min...max)

This should work because Array has an initializer taking a SequenceType and Range conforms to SequenceType . 这应该有效,因为Array有一个初始化器,它使SequenceTypeRange符合SequenceType

Use map 使用map

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

Interesting that you cannot (at least, with Swift 3 and Xcode 8) use Range<Int> object directly: 有趣的是你不能(至少使用Swift 3和Xcode 8)直接使用Range<Int>对象:

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)

Ie, you can use literal only. 即,您只能使用文字。

Since Swift 3/Xcode 8 there is a CountableRange type, which can be handy: 由于Swift 3 / Xcode 8有一个CountableRange类型,它可以很方便:

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 - in循环:

for i in range {
    print(i)
}

You can implement ClosedRange & Range instance intervals with reduce() in functions like this. 您可以使用reduce()在这样的函数中实现ClosedRange和Range实例间隔。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM