ios 快速将 Range<Int> 转换为 [Int]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32103282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
swift convert Range<Int> to [Int]
提问by haitham
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]
得到错误 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.
他们也不工作。
回答by David Skrundz
You need to createan Array<Int>
using the Range<Int>
rather than casting it.
您需要创建一个Array<Int>
usingRange<Int>
而不是cast。
let intArray: [Int] = Array(min...max)
回答by Mr Beardsley
Put the Range in the init.
将范围放在 init.d 文件中。
let intArray = [Int](min...max)
回答by haitham
I figured it out:
我想到了:
let intArray = [Int](min...max)
Giving credit to someone else.
给别人信用。
回答by ad121
do:
做:
let intArray = Array(min...max)
This should work because Array
has an initializer taking a SequenceType
and Range
conforms to SequenceType
.
这应该有效,因为Array
有一个初始化程序采用 aSequenceType
并Range
符合SequenceType
.
回答by vadian
Use map
用 map
let min = 50
let max = 100
let intArray = (min...max).map{let range: Range<Int> = 1...10
let array: [Int] = Array(range) // Error: "doesn't conform to expected type 'Sequence'"
}
回答by devforfu
Interesting that you cannot (at least, with Swift 3 and Xcode 8) use Range<Int>
object directly:
有趣的是,您不能(至少在 Swift 3 和 Xcode 8 中)不能Range<Int>
直接使用对象:
let array: [Int] = Array(range.lowerBound...range.upperBound)
Therefore, as it was mentioned earlier, you need to manually "unwrap" you range like:
因此,正如前面提到的,您需要手动“解开”您的范围,例如:
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]
I.e., you canuse literal only.
即,您只能使用文字。
回答by killobatt
Since Swift 3/Xcode 8 there is a CountableRange
type, which can be handy:
由于 Swift 3/Xcode 8 有一个CountableRange
类型,它可以很方便:
for i in range {
print(i)
}
It can be used directly in for
-in
loops:
它可以直接在for
-in
循环中使用:
func sumClosedRange(_ n: ClosedRange<Int>) -> Int {
return n.reduce(0, +)
}
sumClosedRange(1...10) // 55
回答by Edison
You can implement ClosedRange & Range instance intervals with reduce() in functions like this.
您可以在这样的函数中使用 reduce() 实现 ClosedRange & Range 实例间隔。
func sumRange(_ n: Range<Int>) -> Int {
return n.reduce(0, +)
}
sumRange(1..<11) // 55