封闭范围运算符
封闭范围运算符(a...b) 定义从a 到b 的范围,并包括值a 和b。 a 的值不能大于b。
当迭代一个您希望使用所有值的范围时,封闭范围运算符很有用,例如 for-in 循环:
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
半开范围运算符
半开范围运算符(a..<b) 定义了从a 到b 的范围,但不包括b。之所以说它是半开的,是因为它包含了它的第一个值,而不是它的最终值。与封闭范围运算符一样,a 的值不得大于b。如果a 的值等于b,则结果范围将为空。
当您使用从零开始的列表(例如数组)时,半开范围特别有用,在这种情况下,最多可以计算(但不包括)列表的长度:
let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
print("Person \(i + 1) is called \(names[i])")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack
请注意,该数组包含四个项目,但0..<count 只计算到3(数组中最后一项的索引),因为它是一个半开范围。
封闭范围:a...b
let myRange = 1...3
let myArray = ["a", "b", "c", "d", "e"]
myArray[myRange] // ["b", "c", "d"]
半开范围:a..<b
let myRange = 1..<3
let myArray = ["a", "b", "c", "d", "e"]
myArray[myRange] // ["b", "c"]
这是一个真实的 SpriteKit 示例,我必须使用几乎所有 SpriteKit 项目中的 arc4Random 进行转换。 Random 通常处理范围。
斯威夫特 2
Tools.swift
func randomInRange(_ range: Range<Int>) -> Int {
let count = UInt32(range.upperBound - range.lowerBound)
return Int(arc4random_uniform(count)) + range.lowerBound
}
GameScene.swift
let gap = CGFloat(randomInRange(StackGapMinWidth...maxGap))
斯威夫特 3
Tools.swift
func randomInRange(range: ClosedRange<Int>) -> Int {
let count = UInt32(range.upperBound - range.lowerBound)
return Int(arc4random_uniform(count)) + range.lowerBound
}
GameScene.swift
let gap = CGFloat(randomInRange(range: StackGapMinWidth...maxGap))
所以如果randomInRange()计算给定范围内的随机数,包括上限,那么它应该定义为ClosedRange<Bound>
Migrating to Swift 3
Range 和 ClosedRange 不能被迭代(它们不再是集合),因为仅仅是 Comparable 的值不能递增。
CountableRange 和 CountableClosedRange 需要 Strideable 从它们的绑定中,它们符合 Collection 以便您可以迭代它们。