近期重新學習了一遍Swift語言,主要以《Swift編程權威指南(第2版)》為教程,學習過程中結合比對Java語言特性將學習心得作為三篇筆記:Swift基礎語法,Swift面向對象編程,Swift高級編程。
本文為第一篇《Swift基礎語法》主要涵蓋以下內容
//常量的聲明 let //聲明一個Int常量,常量一旦聲明後不可變化 let num:Int = 2019 print(num)
//變數的聲明 var //聲明一個字元串變數:聲明一個名為name的變數,其類型是String,初始值是」Tom「 var name:String = "Tom"
//總結:對必須變化的實例用變數,其他都用常量
//Switf支持類型推斷:聲明變數或常量時無需聲明類型,編譯器會根據初始值內容進行推斷 let n = 2019 //根據2019內容自行推斷 實例n的類型為Int let firstName = "Nik" var lastName = "Lily" print(n)
```swift
//2. 類型轉換
//3. 浮點數
## 條件語句 #### if-else 由特定的條件邏輯執行代碼,通常要處理一個非此即彼的狀況 ```swift let age = 18 if age > 18{ print("成年人") }else { print("未成年人") }
let age = 58 if age <= 18{ print("未成年人") }else if age<55 { print("青壯年") }else { print("老年人") }
let age = 88 if age > 18{ if age>60{ // print("老年人") }else { print("成年人") } }else { print("未成年人") }
a?b:c 「如果a為真,則執行b;否則執行c」
let age = 20 var result = age > 18 ? "成年人" : "未成年人"; print(result)
&& 邏輯與:當且僅當兩者都為真時結果為真 || 邏輯或:兩者任意之一為真結果為真 ! 邏輯非:真變假,假變真
區別:if else用於處理」非此即彼「的情況,swith用於處理多重條件的情況
ps:先上結論
swith 使用匯總
var code = 401 var erroInfo:String = "erro code is:" switch code { case 200,201,202: print("Http success ") case 300...399: //...區間 print("300系列錯誤") case let code where (code >= 400 && code <= 499) : //where語句的使用,篩選條件 erroInfo += "(code) 400系列錯誤" // fallthrough //不需要匹配進入下一個分支並執行代碼 default: erroInfo += "(code)" //字元串插值 print("其他錯誤") }
var httpcode=400 switch httpcode{ case 200: print(httpcode) case 400: print(httpcode) default: print("default") }
var httpcode=400 switch httpcode{ case 200: print(httpcode) case 400,401,402: print("伺服器異常") default: print("default") }
var httpcode=322 switch httpcode{ case 200: print(httpcode) case 300...399: print(httpcode) case 400,401,402: print("伺服器異常") default: print("default") }
var httpcode=322 var resultstr="" switch httpcode{ case 200: resultstr="OK" case 300...309: resultstr="redirect:(httpcode)" case 400,401,402: resultstr="client erro:(httpcode)" case let unkwnowncode: resultstr="(unkwnowncode) is not known erro code" }
var httpcode=800 switch httpcode{ case 200: print(httpcode) case 300...399: print(httpcode) case 400,401,402: print("伺服器異常") default: print("default httpcode:(httpcode)") }
var httpcode:Int = 205 switch httpcode{ case 200: print(httpcode) case 300...399: print(httpcode) case 400,401,402: print("伺服器異常") case let unknowcode where (unknowcode>201 && unknowcode<208): //指定httpcode 範圍 print("unknowcode where httpcode:(httpcode)") //where default: print("default httpcode:(httpcode)") }
var httpCode=200 var msg="message:" switch httpCode{ case 200: msg+="成功" case 300...399: msg+="重定向" case 400,401,402: msg+="伺服器錯誤" default: msg+="未知" } let erro=(httpCode,msg) //訪問元組 erro.0 erro.1 //通過序號訪問元組元素 //1.9給元組的元素別名 let erro2=(code:httpCode,erroInfo:msg) erro2.code erro2.erroInfo
var firstCode:Int=201 var secondCode:Int=404 let erro=(firstCode,secondCode) switch erro{ case (201,400): print("201,400") case (200,_): print("200,_") case (_,404): print("_,404") default : print("default") }
var age=23 switch age{ case 18...28: print("年輕人") default: print("age =:(age)") //default 語句 } //使用if-case替代,不需要寫不關注的default分支,更關注核心代碼邏輯 var age=23 if case 18...28=age{ print("年輕人") }
var age=26 if case 18...28=age,age>25{ print("大於25歲的年輕人") }
var number:Int = 0; for i in 1...5{ //遍歷 1至5 // print(i) number += 1 print(number) }
for _ in 1...5 { number += 1 print(number) }
for i in 1...10 where i % 3 == 0 { print(" 能被3整除的數:(i)") }
var number:Int = 3 while number > 0 { print(" while 循環 (number)") number -= 1; }
repeat{ print(number) number += 1 }while number <= 3
print(「continue的區別」)
if(i==3)
## 字元串 ```swift var str = "Hello, playground" //聲明字元串變數 let str1 = "Hello" var str2 : String = "HELLO 2" str2.append(" swift") //累加
str += "!" //給可變字元串添加 print(str) print(str.count) //獲取字元串的長度 print(str.contains(str1)) print(str.starts(with: str1)) //print(st) print(str2)
可空類型Optional是Swift的獨特特性,用來指定某個實例沒有值。一個可空類型的實例,要麼已經可用,要麼沒有值就稱為nil。
通過這種方式,編譯器知道實例是否可能為nil,這種顯示的聲明讓代碼更具表達力,也更安全。
var erroInfo :String? //聲明可空類型 ? print(erroInfo) //輸出nil //erroInfo += "test" erroInfo = "test" print(str) //輸出 」Swift「 print(erroInfo) //輸出 Optional("test")
if erroInfo != nil { let theErro = erroInfo! //感嘆號的作用是強制展開可空類型 print(theErro) //輸出"test" }
if let theErrors = erroInfo { //當erroInfo不為nil 則給theErrors賦值,並執行當前代碼塊 print(theErrors) }
var code : Int? code = 401 if let theError = erroInfo, let theCode = code { print("展開多個可空實例") print(theCode) print(theError) }else { print("不滿足") }
if let theError = erroInfo, let theCode = code, code == 402 { print("展開多個可空實例") print(theCode) print(theError) }
數組是有序的
//數組的兩種聲明方式 var data:Array<String> //聲明一個字元串數組 var datas2:[String] //聲明一個字元串數組
var arrs2:[String] = ["xx","yy"] //初始化數組 var arrs = ["a1"] //數組聲明的類型推斷 print(arrs) arrs.append("appenData") print(arrs) arrs[0] += "ap" arrs[1] = "d2" //替換指定下標的元素 print(arrs) print("數組長度count = (arrs.count)") arrs += arrs2 //兩個數組相加 print(arrs) print("------指定位置插入一個元素 EN-------") arrs.insert("EN", at: 2) print(arrs) print(arrs[0...2]) //列印下標前三的元素
var newArr = ["xx","yy"] //判斷兩個數組是否相等,數組是有序的,需元素順序和內容完全一致才算相等 print(newArr == arrs2)
print("常量數組 一旦創建不可修改") let finalArrays = ["a","b"] print(finalArrays) //finalArrays[0] = "66"
集合是無序、元素唯一
//初始化一個集合 var hashSet = Set<String>() //聲明一個String類型的集合 var set1:Set = ["a","b","c"] print(set1)
//集合增加元素 hashSet.insert("a") hashSet.insert("b") print(hashSet) ////循環遍歷插入 for i in 4...8 { hashSet.insert("number (i)") } //print(hashSet)
//包含指定元素 hashSet.contains("a") print(hashSet.contains("a")) //print(hashSet.contains(set1))
//並集 union let newSet = hashSet.union(set1) print(newSet)
//交集 intersection,返回兩個集合的共同部分的集合 let intersectionSet = hashSet.intersection(set1) print("intersection (intersectionSet)")
//不相交,判斷兩個集合是否不相交, 相交則返回false let isDisjointSet = hashSet.isDisjoint(with: set1) print(isDisjointSet)
var dict1 : Dictionary<String , Integer> = [:] var dict2 :[String:Integer] = [:] var dict3 = Dictionary<String,Integer>() var dict4 = [String : Integer]()
var dict :Dictionary<String,Int> = ["Tom":12 , "Jerry":18] var dict2 = ["Tom":12 , "Jerry":18]
var dict :Dictionary<String,Int> = ["Tom":12 , "Jerry":18] //var dict2 = ["Tom":12 , "Jerry":18] //字典初始化的類型推斷 print(dict)
////訪問和修改字典內容 ,key類型默認應為可空的數據n類型 print(dict["Tom"]) //輸出內容為 Optional(12) print(dict["jj"]) //輸出內容為 nil dict["Tom"] = 66 //修改字典的值 print(dict["Tom"]) dict.updateValue(99, forKey: "Jerry") //使用updateValued方法修改字典中指定鍵的值
//print("新建字典元素") //如字典中key為「Jake」的元素不存在則新建,否則則修改; //測試發現字典是無序的,插入的字典值不一定在字典的最末,也可能插入到中間 //dict["Jake"] = 25 //print(dict) ////刪除字典元素 //print("刪除字典元素:removeValue(forkey: ..)") //dict.removeValue(forKey: "Jake") //print(dict)
//循環遍歷字典 for (key,value) in dict{ print("The name is (key), age is (value)") }
//遍歷字典鍵值 for key in dict.keys { print("the dict key is (key)") }
//只遍歷字典的值 for value in dict.values { print("the dict value is (value)") }
let album = ["he":11 , "me":99 , "she":88] print(album.count)
var keys = Array(dict.keys) print(keys) //["Tom", "Jerry"] var values = Array(dict.values) print(values) //[12, 18]
//創建一個字典用於存儲程序開發需要語言,如 key為ios,value為 ["Objective-c","Swift"] print("創建一個字典用於存儲程序開發需要語言") var codeDict = ["ios":["Objective-c","Swift"] , "android":["java","kotlin"]] print(codeDict)
推薦閱讀:
TAG:Swift語言 | iOS開發 |