Swift5.0基礎(chǔ)

溫馨提示:本文記錄的知識點兼容Swift5.0

在 Swift 語言當中,一行代碼就是一個完整的程序。
不用編寫main函數(shù),Swift將全局范圍內(nèi)的首句可執(zhí)行代碼作為程序入口。

一句代碼尾部可以省略分號(;)
多句代碼寫到同一行時必須用分號(;)隔開。

打印

var badg = 12;  
var number = 22;        
// 使用  \(xxxx)進行插值
print("I am:\(number) He is: \(badg)")
print("I am :", badg, "you are:", number )

使用 let來聲明一個常量。不需要修改的,盡量定義成let
使用var來聲明一個變量。
值不要求在編譯時期確定,但使用之前必須賦值1次。

常用數(shù)據(jù)類型:

Bool、Float、Double、String、Character
Array、Dictionary、Set
枚舉類型Operation

  • 字符串

Swift 的 String 和 Character 類型是完全兼容 Unicode 標準的。 Unicode是一個用于在不同書寫系統(tǒng)中對文本進行編碼、表示和處理的國際標準。它使你可以用標準格式表示來自任意語言幾乎所有的字符,并能夠?qū)ξ谋疚募蚓W(wǎng)頁這樣的外部資源中的字符進行讀寫操作。

// 字符串的長度
let lentgh = string0.count
// 使用 + ,字符串拼接
var str0 = "I Love" + "You"
// 使用 == 進行字符串的比較
if str1 == str2 {
  
}
// 判斷字符串是否為空
if str0.isEmpty {
  
}
// 遍歷每一個字符
for cha in String0 {
    print(cha)
}
// 字符串轉(zhuǎn) 數(shù)字
let numString = "123"
let num = Int(numString)   // num 被推測為類型 "Int?", 或者類型 "optional Int"
  • 數(shù)組
let array = [1,2,3,4,5,6,7,8,9]
let num0 = array[0]  // 或 array.first
// 聲明數(shù)組屬性
var datalist : [string] = []
var someInts = [Int]()
var arr0 : Array<Int> = Array()
// 重復元素的數(shù)組
var threeDoubles = Array(repeating: 0.0, count: 3)
// 遍歷數(shù)組
for num in arr0 {
    print(num)
}
// 判斷數(shù)組是否為空
if arr0.isEmpty {
   //...
}
// 是否包含某元素
if arr.contains("x") {
}
// 添加 刪除元素
arr0.append("2")   //在數(shù)組的末尾添加
arr0.append(contentsOf: ["3","4"])
arr0.insert("2", at: 1)
arr0.insert(contentsOf: ["3","4"], at: 0)
arr0.remove(at: 2)

// 數(shù)組可以相加(元素類型需一致)
var arr3 = arr1 + arr2

  • 字典
    字典是一種無序的集合,它存儲的是鍵值對之間的關(guān)系,其所有鍵的值需要是相同的類型,所有值的類型也需要相同。一個字典的 Key 類型必須遵循 Hashable 協(xié)議
// [Key: Value]形式 定義 確定類型的 字典
var dic = [Int: String]()

let dic = [:]   // 空字典
let dict = ["age":18, "height":100, "width":200]
// 鍵值類型 確定
var dic: [String: String] = ["YYZ": "Toronto", "DUB": "Dublin"]

// 鍵值對 個數(shù)
dic.count
// 字典是否為空
if dic.isEmpty {
}
// 更改
let dic1 = dic0.updateValue("Dublin", forKey: "DUB")
// 刪除
dic["APL"] = nil
let dic1 = dic0.removeValue(forKey: "DUB")
// removeValue方法 在鍵值對存在的情況下,會移除該鍵值對并返回被移除的值;
// 在沒有對應(yīng)值的情況下,返回 nil:

// 遍歷
for (key, value) in dic {
    print("\(key): \(value)")
}
// 抽離 鍵值
let arr1 = [String](dic0.keys)  // 返回數(shù)組
let arr2 = [String](dic0.values)

// 排序
dic.keys.sorted()

元組(tuples)

把多個值組合成一個復合值。元組內(nèi)的值可以是任意類型,并不要求是相同類型。

// 定義元組,通過.0 或 .1來訪問內(nèi)部屬性
let http404Error = (404,"網(wǎng)頁不存在")
print(http404Error.0, http404Error.1)

// 定義元組,分別給元組內(nèi)參數(shù)賦值,通過參數(shù)進行訪問
let (statusCode, errorString) = (404,"網(wǎng)頁不存在")
print(statusCode, errorString)

// 使用_,表示不賦值
let (statusCode1, _) = (404,"網(wǎng)頁不存在")
print(statusCode1)

// 通過元組內(nèi)部參數(shù)進行訪問
let http200Status = (statusCode:200, statusString:"請求成功")
print(http200Status.statusCode, http200Status.statusString)

按照Swift標準庫的定義,Void就是空元組`()

流程控制語句

var number = 22
if number == 0 {
  print("ok!")
}else{

} 

guard let location = "xxx" else {
// 如果條件不為真,  則執(zhí)行 else 從句中的代碼。        
}

while number<3 {
  print("ok!")  
}

repeat {
  print("ok!")  
}while number<3

// for-in循環(huán)
let arr = ["Anna", "Alex", "Brian", "Jack"]
for name in arr {
    print("Hello, \(name)!")
}
let dic = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in dic {
// 字典的內(nèi)容理論上是無序的,遍歷元素時的順序是無法確定的
    print("\(animalName)s have \(legCount) legs")
}

區(qū)間運算

閉區(qū)間[a,b]的表示:a...b
半開區(qū)間[a,b)的表示:a..<b
單側(cè)區(qū)間[a,∞)的表示a...

區(qū)間類型ClosedRange、Range、PartialRangeThrough

let rang1: ClosedRange<Int> = 1...3;
let rang2: Range<Int> = 1..<3
let rang3: PartialRangeThrough<Int> = ...3

帶間隔的區(qū)間
[0,2,4,6...100]的表示stride(from: 0, to: 100, by: 2)

for-in循環(huán)

//默認num是let 類型,可以省略
for num in 1...10{
    print(num)
}

//如果要修改 num 的值,需要更改為var類型
for var num in 1...10 {
    num += 100
    print(num)
}
//不需要用到 num ,可以使用_缺省
for _ in 1...10 {
    print("hello,world")
}

設(shè)置間隔的函數(shù):stride(from:to:by:)
for tickMark in stride(from: 0, to: 60, by: 5) {
    // 每5分鐘渲染一個刻度線(0, 5, 10, 15 ... 45, 50, 55)
}

continue語句,使本次循環(huán)結(jié)束,重新開始下次循環(huán)。
break 語句會 立刻結(jié)束整個控制流的執(zhí)行。

區(qū)間運算與數(shù)組

let arr2 = ["aaa", "bbb", "ccc", "ddd"]
for str in arr2[1...2] {
    print(str)    //打印了bbb和ccc
}

switch語句

case、default后面不能寫{}
case之后不必接break
每一個case必須包含至少一條語句
case允許同時判斷多個條件
支持Character、String類型
使用fallthrough可以實現(xiàn)貫穿效果

let name = "c"
switch name {
case "c", "d":   // 可以合并多個條件
    print("ok")
case "a":
    print("ok")
default:
    break
}

可配合區(qū)間、元組

let num = 12
switch num {
case 1...10:
    print("ok")
case 11...20:
    break
default:
    break
}
let point = (1, 1)
switch point {
case (0, 0):
    print("the origin")
case (_, 0):
    print("on the x")
case (0, _):
    print("on the y")
case (-2...2, -2...2):
    print("inside box")
default:
    print("outside box")
}

值綁定:如果有一個值相同,另外一個則會自動綁定

let point1 = (1, 1)
switch point1 {
case (let x, 0):
// 將匹配一個y為 0 的點,并把這個點的橫坐標賦給臨時常量 x;
// 臨時常量可在該case分支 里使用
    print("在x軸")
case (0, let y):
    print("在y軸")
case (let x, 1):
    print("在x軸") 
default:
    print("outside of the box")
}

where關(guān)鍵字

用于判斷某個條件滿足,才會執(zhí)行。

  • 區(qū)間與where
    [10,20,30...100]表示為1...100 where num % 10 == 0
for num in 1...100 where num % 10 == 0 {
    print(num)
}
  • 元組與where
    ??
let point2 = (1, 2) 
// 判斷point2的兩個元素是否相等
switch point2 {
case let (x, y) where x == y:
    print("ok")
case let (x, y) where x != y:
    print("no")
default:
    break
}

關(guān)鍵字 typealias
typealias用來給類型 起別名

typealias Byte  = Int8
typealias Short = Int16
typealias Long  = Int64

typealias Date = (year: Int, month: Int, day: Int)
func test(_ date: Date) {
    print(date.0)
    print(date.year)
}
test((2011, 9, 10))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容