ios - 为什么 stride 函数在 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
.
推荐阅读
- angular - Angular 9:使用 Angular i18n 和服务器端渲染(角度通用)
- python-3.x - 在文件 Python3 中写入浮点数,而不将其转换为字符串
- c# - 无法将类型 void 隐式转换为 int c#
- mysql - 我收到重复的列名,但基于值。当我更改值时,没有错误
- c# - 内部带有 KeyValue 对的自定义配置类
- java - 如何在netbeans中隐藏Jtable?
- r - 多元非线性回归
- salesforce - 在 Salesforce 上报告可见性
- javascript - React Switch 不渲染不同的页面
- java - 未知数量的按钮,如何为每个 JavaFX 添加不同的事件操作