Skip to content

Range 区间

简介

官方文档参考 范围运算符

声明

使用 ... 定义区间

swift
var a = 1...3 // ClosedRange<Int>
var b  = 1..<3 // Range<Int>
var c = ...3  // PartialRangeThrough<Int>
var d = ..<3 // PartialRangeUpTo<Int>
var e = 1... // PartialRangeFrom<Int>
var f  = "a"..."Z"
var g = 0.0...10.0
var h = stride(from:10, to: 100, by: 2) // StrideTo<Int>

获取数组区间

获取区间索引的元素

swift
var a  = ["苹果", "香蕉", "栗子"]

print(a[2...]) // ["栗子"]

遍历区间

for in 可以遍历区间

swift
var a = 5...10

for i in a {
  print(i)
}

判断区间是否包含

contains 方法可判判断区间里是否包含某个元素

swift
var a = 5...10

print(a.contains(8)) // true

区间是否有值

isEmpty 获取区间是否有值

swift
var a = 5...10

print(a.isEmpty) // true

区间上下限

lowerBound 获取区间下限 upperBound 获取区间上限

swift
var a = 5...10

print(a.lowerBound) // 5
print(a.upperBound) // 10