Swift 中的范围与序列:深入解析与实践应用
1. Swift 中的范围(Ranges)
在 Swift 里,范围是数值类型的一个重要方面。整数和浮点类型都遵循 Comparable 协议,这对于支持数值范围操作至关重要。范围并非编译器内置概念,而是标准库的一部分。
Range 是一个泛型结构体,其上下界类型 Bound 需遵循 Comparable 协议。以下是一个简单示例:
enum Number: Comparable {
case zero, one, two, three, four
}
let longForm = Range<Number>(uncheckedBounds: (lower: .one, upper: .three))
let shortForm = Number.one ..< .three
print(shortForm == longForm) // true
范围的一个关键特性是不包含上界:
print(shortForm.contains(.zero)) // false
print(shortForm.contains(.one)) // true
print(shortForm.contains(.two)) // true
print(shortForm.contains(.three)
超级会员免费看
订阅专栏 解锁全文
6

被折叠的 条评论
为什么被折叠?



