最近在学习Swift,学习中我遇到了几个小问题。

我找到一本《Swift基础教程》,正在按照书中的内容学习。这本书的内容很简洁易懂,很适合新手。但是可能由于书中演示的 Swift 版本不同的关系,我遇到了几个问题。书中使用的是 Xcode 6 ,而我使用的版本是 Xcode 13 。

问题一

书中的提到可以使用 println 函数打印内容。但是我如果使用 println 则会报错。

问题二

书中有一个示例是这样的

var speedLimit = 75
var carSpeed = 0

while (carSpeed < 100) {
    carSpeed ++
    switch carSpeed {
    case 0..<20:
        print("\(carSpeed): You're going really slow")
    case 20..<30:
        print("\(carSpeed): Pick up the pace")
    case 30..<40:
        print("\(carSpeed): Tap the accelerator")
    case 40..<50:
        print("\(carSpeed): Hitting your stride")
    case 50..<60:
        print("\(carSpeed): Moving at a good clip")
    case 60..<70:
        print("\(carSpeed): Now you're cruising!")
    case 70...speedLimit:
        print("\(carSpeed): Warning... approaching the seed limit")
    default:
        print("\(carSpeed): You're going too fast!")
    }
    if carSpeed > speedLimit {
        break
    }
}

但是这样输入之后在 switch carSpeed { 后面会报错 Expected expression after operator 。同时下面也会有错误提示

error: Playground.playground:6:5: error: expected expression after operator
    switch carSpeed {
    ^

一开始我以为是 switch 用法不对,但是后来才发现这个错误是针对第5行的语句的。将代码改成这样就可以了

var speedLimit = 75
var carSpeed = 0

while (carSpeed < 100) {
-    carSpeed ++
+    carSpeed = carSpeed + 1
    switch carSpeed {
    case 0..<20:
        print("\(carSpeed): You're going really slow")
    case 20..<30:
        print("\(carSpeed): Pick up the pace")
    case 30..<40:
        print("\(carSpeed): Tap the accelerator")
    case 40..<50:
        print("\(carSpeed): Hitting your stride")
    case 50..<60:
        print("\(carSpeed): Moving at a good clip")
    case 60..<70:
        print("\(carSpeed): Now you're cruising!")
    case 70...speedLimit:
        print("\(carSpeed): Warning... approaching the seed limit")
    default:
        print("\(carSpeed): You're going too fast!")
    }
    if carSpeed > speedLimit {
        break
    }
}

个人认为这是 Swift 为了避免写代码时搞不清楚某个变量的具体变化而引入的机制吧。避免大家在使用某个变量前通过 ++ 等方式修改变量。如果做一个测试就会发现,为了避免混淆 Swift 中已经不支持 ++-- 等操作了。如果输入下面的代码

var i
i ++

Xcode 会提示

error: cannot find operator '++' in scope; did you mean '+= 1'?