- 大致原因是影响那些把Swift作为第一语言的学习者的学习;Swift的新特性(下面代码对比)完全可以取代这些单目运算符等等
- 弃用原因详情点击这里
for i = 0; i < n; i++
{
...
}
for i in 0..<n
{
...
}
- ++你需要写+=
var x = 1
//Increment
x += 1 //Means x = x + 1
- 递减--,你需要写-=
var x = 1
//Decrement
x -= 1 //Means x = x - 1
对于for循环:
增量示例:
代替
for var index = 0; index < 3; index ++ {
print("index is \(index)")
}
- 你可以写:
//Example 1
for index in 0..<3 {
print("index is \(index)")
}
//Example 2
for index in 0..<someArray.count {
print("index is \(index)")
}
//Example 3
for index in 0...(someArray.count - 1) {
print("index is \(index)")
}
- 递减示例:
for var index = 3; index >= 0; --index {
print(index)
}
- 你可以写:
for index in 3.stride(to: 1, by: -1) {
print(index)
}
//prints 3, 2
for index in 3.stride(through: 1, by: -1) {
print(index)
}
//prints 3, 2, 1
for index in (0 ..< 3).reverse() {
print(index)
}
for index in (0 ... 3).reverse() {
print(index)
}