-
for循環(huán)的高級(jí)遍歷
-
一砌些、遍歷子控件而且指定是UILabel的控件才打印
-
二、使用Where關(guān)鍵字查找名字
-
-
三抢肛、遍歷中包含可選值
-
通常寫法:打印出來的是可選值
-
優(yōu)化寫法:使用 case let name? 打印出來的不是可選值
-
通常寫法:打印出來的是可選值
-
nil的用法
如果使用了可選類型喷好,那么是非常危險(xiǎn)的,通常就需要通過“!”強(qiáng)制解包癞谒,這就會(huì)導(dǎo)致程序崩潰(Crash)。Swift提供了一個(gè)
??
的操作符,如果可選類型為nil弹砚,會(huì)讓它默認(rèn)值- eg: 舉個(gè)
let name: String? = "MG"
let otherName = name ?? "小明"
print(otherName)
// 打印出來的是 `MG`
let name: String? = nil
let otherName = name ?? "小明"
print(otherName)
// 打印出來的是 `小明
一般與關(guān)鍵字try連用
- #####使用do try catch
- #####使用try? 可以簡化成這樣
- #####Optional binding(可選綁定)
if let unwrappedAuthorName = authorName {
print("Author is \(unwrappedAuthorName)")
} else {
print("No author.")
}
-
Lazy Loading
- eg:舉個(gè)
-
普通
class Person {
let name: String
init(name: String) {
self.name = name
}
func reversedName() -> String { // 字符串反轉(zhuǎn)方法
return "\(name.uppercased()) backwords is \(String(name.uppercased().characters.reversed()))"
}
}
let person = Person(name: "ming Swift")
print(person.reversedName())
> - #Lazy
class Person {
let name: String
lazy var reversedName: String = self.getReversedName()
init(name: String) {
self.name = name
}
private func getReversedName() -> String { // 字符串反轉(zhuǎn)方法
return "\(name.uppercased()) backwords is \(String(name.uppercased().characters.reversed()))"
}
}
let person = Person(name: "ming Swift")
print(person.reversedName)
打印出來的字符串是 “MING SWIFT backwords is TFIWS GNIM”
-
goto用法
- 我們來看普通的方法
var board = [[String]](repeating: [String](repeating: "",
count: 10), count: 10)
board[3][5] = "x"
for (rowIndex, cols) in board.enumerated() {
for (colIndex, col) in cols.enumerated() {
if col == "x" {
print("Found the treasure at row \(rowIndex) col \(colIndex)!")
}
}
}
解釋:雖然打印出來我們想要的結(jié)果双仍,但是這段代碼做了很多無用功。如果一開始搜索的找到的時(shí)候就使用break跳出循環(huán)迅栅。往下看看:
var board = [[String]](repeating: [String](repeating: "",
count: 10), count: 10)
board[3][5] = "x"
for (rowIndex, cols) in board.enumerated() {
for (colIndex, col) in cols.enumerated() {
if col == "x" {
print("Found the treasure at row \(rowIndex) col \(colIndex)!")
break
}
}
}
解釋:然而殊校,使用break也只是結(jié)束了當(dāng)前的循環(huán),so it would exit the for (colIndex, col) loop then continue running the for (rowIndex, cols) loop.(for (colIndex, col)這個(gè)循環(huán)直到跑完for (rowIndex, cols)
循環(huán)才會(huì)退出)读存,這也浪費(fèi)了一些時(shí)間。我們繼續(xù)往下看更優(yōu)化的代碼:
var board = [[String]](repeating: [String](repeating: "",
count: 10), count: 10)
board[3][5] = "x"
rowLoop: for (rowIndex, cols) in board.enumerated() {
for (colIndex, col) in cols.enumerated() {
if col == "x" {
print("Found the treasure at row \(rowIndex) col \(colIndex)!")
break rowLoop
}
}
}
解釋:標(biāo)記你的循環(huán)呕屎。這會(huì)立即跳出循環(huán),和結(jié)束后for (rowIndex, cols)
循環(huán)——完美让簿。
再舉個(gè)
- 未優(yōu)化代碼,層層嵌套
if userRequestedPrint() {
if documentSaved() {
if userAuthenticated() {
if connectToNetwork() {
if uploadDocument("resignation.doc") {
if printDocument() {
print("Printed successfully!")
}
}
}
}
}
}
- 優(yōu)化后的代碼:使用Guard之后秀睛,層級(jí)會(huì)變得非常清晰尔当,這樣的代碼可讀性非常強(qiáng)
printing: if userRequestedPrint() {
guard documentSaved() else { break printing }
guard userAuthenticated() else { break printing }
guard connectToNetwork() else { break printing }
guard uploadDocument("work.doc") else { break printing }
guard printDocument() else { break printing }
print("Printed successfully!")
}
-
enum枚舉和Struct結(jié)構(gòu)體
-
eg:倫敦這個(gè)地方,有叫地理位置蹂安。有地鐵路線以及旅游景點(diǎn)椭迎。其中一個(gè)常量:地理位置,兩個(gè)嵌套的枚舉:地鐵路線以及旅游景點(diǎn)是一個(gè)枚舉田盈。
-
enum London {
static let coordinates = (lat: 51.507222, long: -0.1275) // 地理位置(經(jīng)緯度)
enum SubwayLines { // 地鐵路線
case Bakerloo, Central, Circle, District, Elizabeth,HammersmithCity, Jubilee, Metropolitan, Northern, Piccadilly,
Victoria, WaterlooCity
}
enum Places { // 位置
case BuckinghamPalace, CityHall, OldBailey, Piccadilly,StPaulsCathedral
}
}
舉個(gè) 枚舉
enum R {
enum Storyboards: String {
case Main, Detail, Upgrade, Share, Help
}
enum Images: String {
case Welcome, Home, About, Button
}
}
// 外界使用:現(xiàn)在流行的SnapKit畜号,MJRefresh等度有自己的前綴開頭也許就是這樣搞的
let home = R.Images.Home // 這樣層級(jí)也很清晰
舉個(gè) 枚舉和結(jié)構(gòu)體
struct Deck {
struct Card {
enum Suit {
case Hearts, Diamonds, Clubs, Spades
}
var rank: Int
var suit: Suit
}
var cards = [Card]()
}
// 外界使用:現(xiàn)在流行的SnapKit,MJRefresh等度有自己的前綴開頭也許就是這樣搞的
let hearts = Deck.Card.Suit.Hearts // 這樣層級(jí)也很清晰