
[英]Why does CGAffineTransformMakeRotation not work in Swift?
[英]Why does stride function work like this in Swift?
在第一個代碼片段下方打印 1
for i in stride(from: 1, through: 1, by: -1) {
print(i)
}
但是為什么下面的代碼段什么也沒打印?
for i in stride(from: 1, through: 2, by: -1) {
print(i)
}
對於正的步幅量, stride(from:through:by:)
返回滿足x
的所有值的序列
start <= x and x <= end
可以通過將步幅添加零次或多次來從起始值到達。 對於負步幅,條件是相反的:
start >= x and x >= end
這種行為關於正向和負向步幅是對稱的:
for i in stride(from: 0, through: 0, by: 1) { print(i) } // prints 0
for i in stride(from: 0, through: -1, by: 1) { print(i) } // prints nothing
for i in stride(from: 0, through: 0, by: -1) { print(i) } // prints 0
for i in stride(from: 0, through: 1, by: -1) { print(i) } // prints nothing
該實現可以在Swift源代碼庫中的 Stride.swift 中找到:
public mutating func next() -> Element? {
let result = _current.value
if _stride > 0 ? result >= _end : result <= _end {
// Note the `>=` and `<=` operators above. When `result == _end`, the
// following check is needed to prevent advancing `_current` past the
// representable bounds of the `Strideable` type unnecessarily.
//
// If the `Strideable` type is a fixed-width integer, overflowed results
// are represented using a sentinel value for `_current.index`, `Int.min`.
if result == _end && !_didReturnEnd && _current.index != .min {
_didReturnEnd = true
return result
}
return nil
}
_current = Element._step(after: _current, from: _start, by: _stride)
return result
}
你的第一個例子
for i in stride(from: 1, through: 1, by: -1) { print(i) }
打印1
因為該值滿足1 >= 1
和1 >= 1
。 你的第二個例子
for i in stride(from: 1, through: 2, by: -1) { print(i) }
什么都不打印,因為沒有值同時滿足條件1 >= x
和x >= 2
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.