什么样的类型在for循环中有范围?

What kind of type have the range in for loop?(什么样的类型在for循环中有范围?)
本文介绍了什么样的类型在for循环中有范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们编写以下内容时:

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循环中有范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)