1. 程式人生 > >Swift學習 --- 2.1基礎部分

Swift學習 --- 2.1基礎部分

edit xcod ror option 復合 tis 換行 xcode mon

1.swift 能夠省去;


2.println與print的差別就是一個能夠換行一個不能夠


3.swift省去了.h與.m 直接一個swift文件


4.元組能夠返回多個值,元組(tuples)把多個值組合成一個復合值。

元組內的值能夠使隨意類型,並不要求是同樣類型,你能夠將一個元組的內容分解(decompose)成單獨的常量和變量。然後你就能夠正常使用它們了:

let (statusCode, statusMessage) = http404Error
println("The status code is \(statusCode)"
)

假設你僅僅須要一部分元組值,分解的時候能夠把要忽略的部分用下劃線(_)標記:
let (justTheStatusCode, _) = http404Error
println("The status code is \(justTheStatusCode)")
// 輸出"The status code is 404"


此外,你還能夠通過下標來訪問元組中的單個元素。下標從零開始:

println("The status code is \(http404Error.0)")
// 輸出"The status code is 404"
println("The status message is \(http404Error.1)"
)
// 輸出"The status message is Not Found"

你能夠在定義元組的時候給單個元素命名:
let http200Status = (statusCode:200, description:"OK")


給元組中的元素命名後,你能夠通過名字來獲取這些元素的值:

println("The status code is \(http200Status.statusCode)")
// 輸出"The status code is 200"
println("The status message is \(http200Status.description)")
// 輸出"The status message is OK"


5.nil能夠用在常量上,也能夠用在變量上.

Swiftnil Objective-C中的nil並不一樣。

Objective-C中,nil是一個指向不存在對象的指針。在 Swift 中。nil不是指針——它是一個確定的值。用來表示值缺失。不論什麽類型的可選都能夠被設置為nil,不僅僅是對象類型。

nil不能用於非可選的常量和變量。

假設你的代碼中有常量或者變量須要處理值缺失的情況,請把它們聲明成相應的可選類型?//let?test :?String?=?nil 這是錯的

假設你聲明一個可選常量或者變量可是沒有賦值,它們會自己主動被設置為nil
var surveyAnswer: String?
// surveyAnswer 被自己主動設置為 nil
? ? ? ??

6.假設相對變量的類型進行鎖定,能夠用?“?:?“ 來確定,比如 :String,聲明中的冒號代表著“是類型”(只是一般Xcode會幫你自己主動推斷類型)


7.swift str轉int 類型是str.toInt()的方法,轉str眼下僅僅會str.bridgeToObjectiveC().doubleValue,str.toInt()返回的是一個可選類型,也就是說能夠為nil


8.能夠用typealias進行類型別名


9.assertion 斷言 通過一個推斷能夠進行調試(可帶信息打印)


10.var possibleString:String?

=nil

//let possibleString: String? = "An optional string."??????? println(possibleString)

//println(possibleString!)加嘆號會蹦使用!來獲取一個不存在的可選值會導致執行時錯誤。使用!來強制解析值之前,一定要確定可選包括一個非nil的值。

Swift學習 --- 2.1基礎部分