2.1 開始學習Swift
2.2 在Playgrounds中測試Swift
2.3 常數與變數
import UIKit
let constant = 10
var y = 10
var x = y + constant
import UIKit
let constant = 10
var number = 10
var x = number + constant
contant = 20
number = 50
2.4 了解型態推論
import UIKit
let constant: Int = 10
var number: Int = 10
var result: Int = number + constant
Int 表示這個變數or常數的型態,是一種整數。
Double 表示這個變數or常數的型態,是一種小數。
String 表示一串文字。
Bool 意思是布林(boolean)值,表示 true 或 false。
var number: Double = 10.5
import UIKit
let constant: Int = 10
var number: Double = 10.5
var result: Double = number + Double(constant)
2.5 文字的處理
var messsage = "The best way to get started is to stop talking and code."
import UIKit
var messsage = "The best way to get started is to stop talking and code."
let messsage = "The best way to get started is to stop talking and code."
import UIKit
var greeting = "Hello "
var name = "Vivian"
var message = greeting + name
uppercased() 可以把字串轉換成大寫。
lowercased() 可以把字串轉換成小寫。
message.count 可以計算一個字串有幾個字元。
import UIKit
var greeting = "Hello "
var name = "Vivian"
var message = greeting + name
message.uppercased()
message.lowercased()
message.count
(1)實作案例:顯示購買書本的總價
var bookPrice = 39
var numOfCopies = 5
var totalPrice = bookPrice * numOfCopies
var totalPriceMessage = "The price of the book is $" + totalPrice
var bookPrice = 39
var numOfCopies = 5
var totalPrice = bookPrice * numOfCopies
var totalPriceMessage = "The price of the book is $" + String(totalPrice)
var bookPrice = 39
var numOfCopies = 5
var totalPrice = bookPrice * numOfCopies
var totalPriceMessage = "The price of the book is $ \(totalPrice)"
2.6 流程控制
var timeYouWakeUp = 6
if timeYouWakeUp == 6 {
print("Cook yourself a big breakfast!")
} else {
print("Go out for breakfast.")
}
- 如果你獲得10,000的獎金(或者更多),你將決定到巴黎或倫敦旅行。
- 如果你獲得5000至9999之間的獎金,你將決定到東京旅行。
- 如果你獲得1000至4999之間的獎金,你將決定到曼谷旅行。
- 如果獎金少於1000 ,則待在家中。
var bonus = 5000
if bonus >= 10000 {
print("I will travel to Paris and London!")
} else if bonus >= 5000 && bonus < 10000{
print("I will travel to Tokyo.")
} else if bonus >= 1000 && bonus < 5000{
print("I will travel to Bangkok.")
} else {
print("Just stay home.")
}
import UIKit
var bonus = 5000
switch bonus {
case 10000...:
print("I will travel to Paris and London!")
case 5000...9999:
print("I will travel to Tokyo.")
case 1000...4999:
print("I will travel to Bangkok.")
default:
print("Just stay home.")
}
2.7 了解Array與字典
(1)陣列
var bookCollection = ["Tool of Titans","Rework","Your Move"]
bookCollection[0]
var bookCollection = ["Tool of Titans","Rework","Your Move"]
bookCollection[0]
bookCollection.append("Authority")
bookCollection.count
var bookCollection = ["Tool of Titans","Rework","Your Move"]
bookCollection[0]
bookCollection.append("Authority")
bookCollection.count
var bookCollection = ["Tool of Titans","Rework","Your Move"]
bookCollection[0]
bookCollection.append("Authority")
bookCollection.count
for index in 0...3 {
print(bookCollection[index])
}
var bookCollection = ["Tool of Titans","Rework","Your Move"]
bookCollection[0]
bookCollection.append("Authority")
bookCollection.count
for index in 0...bookCollection.count - 1 {
print(bookCollection[index])
}
for book in bookCollection {
print(book)
}
(2)字典
import UIKit
var bookCollectionDic = ["1328683788":"Tool of Titans","0307463745":"Rework","1612060919":"Authority"]
bookCollectionDic["0307463745"]
for (key, value) in bookCollectionDic{
print("ISBN:\(key)")
print("Title:\(value)")
}
實作案例:建立一個表情符號字典
import UIKit
var emojiDict: [String:String] = ["👻":"Ghost",
"💩":"Popp",
"😤":"Angry",
"😱":"Scream",
"👾":"Alien minster" ]
var wordToLookup = "👻"
var meaning = emojiDict[wordToLookup]
print(meaning)
wordToLookup = "👾"
meaning = emojiDict[wordToLookup]
print(meaning)
(3)陣列和字典的差異
- 元素的存取方式不同:陣列可以透過索引(index)來存取元素,而字典則是透過鍵(key)來存取元素。
- 元素的排序方式不同:陣列是按照元素插入的順序來排序的,而字典則是無序的。
- 元素的型態不同:陣列的元素可以是同一個型別或不同的型別,而字典的元素通常是同一個型態的鍵值對(key-value pair)。
2.8 了解Optionals
var jobTitle: String?
var message = "Your job title is" + jobTitle
if let 在 Swift 語言中,是一種對 Optional 變數強制解開(forced unwrapping)的方式,以確保其值存在。它可以在 Optional 變數有值時,將其解開(unwrap)並綁定到一個新的變數中,以便在 if 語句塊中使用。如果 Optional 變數為 nil,則 if 語句塊中的代碼將被跳過。這樣可以避免因為 nil 值造成的錯誤。
當 meaning 不為 nil 時,將其解包並指定給一個新的變數 let meaning,進而執行大括號內的程式碼。如果 meaning 為 nil,則不會進入該程式碼。當 meaning 為非 nil 值時,會印出 meaning 的值。
2.9 玩玩UI
import UIKit
var emojiDict = ["👻": "Ghost", "🤖": "Robot", "😤": "Angry", "🤓": "Nerdy", "👾": "Alien monster"]
var wordToLookup = "🤓"
var meaning = emojiDict[wordToLookup]
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
containerView.backgroundColor = UIColor.orange
let emojiLabel = UILabel(frame: CGRect(x: 95, y: 20, width: 150, height: 150))
emojiLabel.text = wordToLookup
emojiLabel.font = UIFont.systemFont(ofSize: 100.0)
containerView.addSubview(emojiLabel)
let meaningLabel = UILabel(frame: CGRect(x: 110, y: 100, width: 150, height: 150))
meaningLabel.text = meaning
meaningLabel.font = UIFont.systemFont(ofSize: 30.0)
meaningLabel.textColor = UIColor.white
containerView.addSubview(meaningLabel)