问题描述
当我们编写以下内容时:
When we write the following:
for i in 1...10 {
//do stuff
}
我想知道在函数调用中使用范围 1...10
的类型,例如:
I want know what type have the range 1...10
to use it in function call for example:
myFunc(1...10)
推荐答案
如果你在定义let range = 1..<10
之后下一个断点,你会发现其实不是Range
结构,但评估一个 CountableRange
(或 CountableClosedRange
表示 0...10)
If you put a breakpoint after defining let range = 1..<10
, you will see that it's actually not a Range
structure, but rater a CountableRange
(or CountableClosedRange
for 0...10)
文档:CountableRange、CountableClosedRange
功能:
func printRange(range: CountableRange<Int>) {
for i in range { print ("(i)") }
}
func printRange(range: CountableClosedRange<Int>) {
for i in range { print ("(i)") }
}
用法:
let range = 1..<10
printRange(range: range)
let closedRange = 1...10
printRange(range: closedRange)
通用函数:
由于两个结构都符合 RandomAccessCollection
协议,因此您只能像这样实现一个功能:
Since both structs conform to RandomAccessCollection
protocol, you can implement only one function like this:
func printRange<R>(range: R) where R: RandomAccessCollection {
for i in range { print ("(i)") }
}
这篇文章关于 Swift 3 中的范围也可能有用.
This article about ranges in Swift 3 may also be useful.
这篇关于什么样的类型在for循环中有范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!