參考網站
- http://bone.twbbs.org.tw/blog/2397.html
- http://tommy60703.gitbooks.io/swift-language-traditional-chinese/
/*
* 練習For迴圈與IF判斷
*/
let individualScores = [75,43,103,87,12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
}else {
teamScore += 1
}
}
teamScore
/*
* 複合值Tuples練習
*/
let http404Error = (404, "Not Found")
let (statusCode, statusMessage) = http404Error
println("The status code is \(statusCode)")
println("The status message is \(statusMessage)")
/*
* 複合值Tuples練習二
*/
let http200Status = (statusCode: 200, description: "OK")
println("The status code is \(http200Status.statusCode)")
println("The status message is \(http200Status.description)")
/*
* 型別轉換
*/
let possibleNumber = "123" //當入123型別可以正常轉換,但是輸入Hello會傳回nil
let convertedNumber = possibleNumber.toInt()
// convertedNumber 被推測為型別 "Int?", 或者型別 "optional Int"
if convertedNumber == 123 {
println("\(possibleNumber) has an integer value of \(convertedNumber!)")
} else {
println("\(possibleNumber) could not be converted to an integer")
}
/* * 隱式解析 Optionals */ let possibleString: String? = "An optional string." println(possibleString!) // 需要驚嘆號來獲取值 let assumedString: String! = "An implicitly unwrapped optional string." println(assumedString) // 不需要感嘆號
/* * 除錯用 */ let age = -3 assert(age >= 0, "A person's age cannot be less than zero") // 因為 age < 0,所以assertion會觸發
/*
* 運算元練習
*/
var i = 10
var x = 0
x = i++ //LOAD i (現在暫存器上的值是 10)
// STORE x (所以現在 x = 10,暫存器還是 10)
// ADD 1 (現在暫存器上的值是 11)
// STORE i (現在 i = 11)
var j = 10
var y = 0
y = ++j // LOAD j (現在暫存器上的值是 10)
// ADD 1 (現在暫存器上的值是 11)
// STORE j (現在 j = 11)
// STORE y (現在 y = 11)
println("x = \(x)"); // x = 10
println("y = \(y)"); // y = 11
沒有留言:
張貼留言