What kind of type have the range in for loop?

五迷三道 提交于 2019-12-21 20:35:06

问题


When we write the following:

for i in 1...10 {
//do stuff
}

I want know what type have the range 1...10 to use it in function call for example:

myFunc(1...10)

回答1:


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)

Docs: CountableRange, CountableClosedRange

Functions:

func printRange(range: CountableRange<Int>) {
    for i in range { print ("\(i)") }
}

func printRange(range: CountableClosedRange<Int>) {
    for i in range { print ("\(i)") }
}

Usage:

let range = 1..<10
printRange(range: range)

let closedRange = 1...10
printRange(range: closedRange)

Generic function:

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

This article about ranges in Swift 3 may also be useful.




回答2:


for i in 1...10 {
      print(i)
}

Output : 1 2 3 4 5 6 7 8 9 10

your this loop is run 10 time if you start it with 0 then your loop run 11 time . hope you clear with start with 0 and 1 what is different

and ya as you ask that myfunc(1...10) that means

Range(1..<11)
  - startIndex : 1
  - endIndex : 11



回答3:


These are called Ranges (see here - https://developer.apple.com/reference/swift/range)

So myfunc would be declared as

func myfunc(range: Range)



来源:https://stackoverflow.com/questions/40123570/what-kind-of-type-have-the-range-in-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!