程式寫錯地方的 Expressions are not allowed at the top level 和 Expected declaration
開發 iOS App 時,最重要的事莫過於寫程式了。但是程式寫的位置很重要,可不是任何地方都能寫。比方以下兩種情況是初學者常遇到的錯誤。
- 在型別定義的 { } 裡, func 的 { } 之外寫程式。
- 在 top level 寫程式。
1 在型別定義的 { } 裡, func 的 { } 之外寫程式。
第 21 行的 lyrics = lyrics + "I gave you my heart"
造成錯誤 Expected declaration。
在型別定義的 { },基本上只會有以下三種東西的宣告(declaration):
- 利用變數(常數)宣告的屬性。
- 利用 function 定義的方法。
- 另一個型別的定義。(nested type)
比方以下例子。
class Baby {
var age = 1
var name = "peter"
func sleep() {
print("sleep")
}
}
剛剛的程式 lyrics = lyrics + "I gave you my heart"
不是宣告,所以出現錯誤 Expected declaration(預期的程式應該要是某個東西的宣告,比方變數,function,型別的宣告。)。
2 在 top level 寫程式。
第 22 行的 lyrics = lyrics + "I gave you my heart"
造成錯誤 Expressions are not allowed at the top level。
Expressions are not allowed at the top level
裡的 top level 指的是不被任何 { } 包含的區塊,因此第 11 行 ~ 13 行是 top level。在 top level 我們只能出現以下三種程式:
- 宣告變數(常數)。
- 定義 function 。
- 定義型別。
因此像 print("原來你是 我最想留住的幸運")
這樣的程式是無法出現在 top level 的。值得注意的,在 playground 剛剛的程式是允許的,這是因為 playground 是特殊的執行環境。