Swift是Apple在2014年所提出的程式語言,
它簡化了傳統Object-C的寫法,
在寫法上更像是C#和Python 結合的高階語言,
很適合學習和記憶。
此外,蘋果為Swift語言發明了一個名為Playground(練功遊樂場)
在這裡可以將自己的創意投入、撰寫並執行,
讓自己知道靈光一現的想法是否有執行性。
建立playground
開啟Xcode軟體,建立一個playgroud專案,
透過我們可以快速練習 swift 4 語法,並可以快速偵錯和編譯
變數var和常數let
// 使用 let 宣告常數 name
let name = "Joe"
// 使用 var 宣告變數 price
var price = 300
// 接著就可以使用這個宣告過的常數 用來印出名字
print(name)
重複結構
for-in loop
// 一個一到三的閉區間
for index in 1...3 {
print(index)
}
// 會依序印出:
// 1
// 2
// 3
while loop
var n = 2
while n < 20 {
n = n * 2
}
// 印出:32
print(n)
流程控制
If..Else
var score = 25
if score < 60 {
score = score + 50
} else {
score = score + 20
}
print(score) // 現在 score 等於 75
Switch…Case…
var timeYouWakeUp = 6
switch timeYouWakeUp {
case 6:
print("Cook yourself a big breakfast!")
default:
print("Go out for breakfast")
}
函數
使用func
關鍵字
// 定義一個將兩個整數相加的函式
func addTwoInts(number1: Int, number2: Int) -> Int {
return number1 + number2
}
Array的格式
var bookCollection = ["Tool of Titans", "Rework", "Your Move"]
Dictionary的格式
var bookCollectionDict = ["1328683788": "Tool of Titans", "0307463745": "Rework", "1612060919": "Authority"]
類別
class GameCharacter {
var stats = CharacterStats()
var attackSpeed = 1.0
var name: String?
}