结构
Closed
ClosedRange
从下限到上限(包括上限)的区间。
声明
@frozen struct ClosedRange<Bound> where Bound : Comparable
概述
您可以使用封闭范围运算符 (...
) 创建 ClosedRange
实例。
let throughFive = 0...5
ClosedRange
实例包含其下限和上限。
throughFive.contains(3)
// true
throughFive.contains(10)
// false
throughFive.contains(5)
// true
因为封闭范围包括其上限,所以下限等于上限的封闭范围包含该值。因此,ClosedRange
实例不能表示空范围。
let zeroInclusive = 0...0
zeroInclusive.contains(0)
// true
zeroInclusive.isEmpty
// false
使用封闭范围作为连续值的集合
当封闭范围使用整数作为其下限和上限,或任何其他符合 Strideable
协议且具有整数步长的类型时,您可以在 for
- in
循环中使用该范围,或使用任何序列或采集方法。范围的元素是从其下限到(包括)其上限的连续值。
for n in 3...5 {
print(n)
}
// Prints "3"
// Prints "4"
// Prints "5"
因为Float
和Double
等浮点类型是它们自己的Stride
类型,所以它们不能用作可数范围的边界。如果您需要迭代连续的浮点值,请参阅stride(from:through:by:)
函数。
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相关用法
- Swift ClosedRange.Index ..<(_:)用法及代码示例
- Swift ClosedRange index(_:offsetBy:)用法及代码示例
- Swift ClosedRange.Index ..<(_:_:)用法及代码示例
- Swift ClosedRange ~=(_:_:)用法及代码示例
- Swift ClosedRange clamped(to:)用法及代码示例
- Swift ClosedRange relative(to:)用法及代码示例
- Swift ClosedRange.Index ...(_:_:)用法及代码示例
- Swift ClosedRange subscript(_:)用法及代码示例
- Swift ClosedRange ==(_:_:)用法及代码示例
- Swift ClosedRange.Index ...(_:)用法及代码示例
- Swift CollectionDifference firstIndex(of:)用法及代码示例
- Swift Collection prefix(upTo:)用法及代码示例
- Swift ContiguousArray forEach(_:)用法及代码示例
- Swift CollectionOfOne contains(_:)用法及代码示例
- Swift Collection first用法及代码示例
- Swift Character lowercased()用法及代码示例
- Swift ContiguousArray insert(contentsOf:at:)用法及代码示例
- Swift CollectionOfOne compactMap(_:)用法及代码示例
- Swift CollectionDifference contains(where:)用法及代码示例
- Swift CollectionOfOne last(where:)用法及代码示例
- Swift Collection dropLast(_:)用法及代码示例
- Swift ContiguousArray reserveCapacity(_:)用法及代码示例
- Swift Comparable ...(_:)用法及代码示例
- Swift ContiguousArray lexicographicallyPrecedes(_:)用法及代码示例
- Swift ContiguousArray elementsEqual(_:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 ClosedRange。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。