Swift 基础教程:区间运算符

区间运算符(Range Operators)有2种

  • 闭区间运算符(n…m),n 不能大于 m,相当于数学的 [n, m]
  • 半开区间运算符(n…<m),相当于数学的 [n, m)

区间运算符一般与 for-in 组合

/// 闭区间运算符
for index in 0...3 {
    print(index)
}
// 0
// 1
// 2
// 3

/// 半开区间运算符
for index in 0..<3 {
    print(index)
}
// 0
// 1
// 2

区间运算符可以方便遍历数组全部或连续多个元素

let array = ["one", "two",  "three",  "four",  "five"]

/// 遍历连续多个元素
for index in 1...3 {
    print(array[index])
}
// two
// three
// four

/// 遍历全部元素
for index in 0..<array.count {
    print(array[index])
}
// one
// two
// three
// four
// five

猜你喜欢

转载自blog.csdn.net/yao1500/article/details/106255542