Swift 運算子和 Range

2021-08-20 18:53:20 字數 2368 閱讀 4036

//一. 基本運算子(basic operators)

//數字運算子,邏輯運算子等大多數標準的c語言運算子,數字運算子可以檢測運算結果避免溢位(超出儲存型別允許的值的範圍)

//1. 一元運算子(unary operators)

//賦值運算子(assignment operator): =

let b = 7; var a = 10; a = b

var (x, y) = (1, 2)

/*和c ,oc 的賦值運算子不同,swift中的賦值運算子不會返回乙個值

if x = y

*///2. 二元運算子(binary operators)

//和c ,oc 的數字運算子不同,swift中的數字運算子不允許值溢位,可以使用swift的溢位運算子來操作

//(1) + 運算子, + 支援字串拼接

print("hello, " + "world") //輸出:hello, world

// + , - 用於一元運算子時表示正負

let minussix = -6; let alsominussix = +minussix

//(2) 求餘運算子(remainder operator): %

// -9 % 4 = -1 9 % -4 = -1

//(3) 復合賦值運算子(compound assignment operators)

var anum = 1; a += 2 //a = a + 2

//復合運算子沒有返回值,不能用來賦值

// let b = a += 2 (不合法)

//(4) 比較運算子: ==,>,<,!=,>=,<=, 比較運算子不能用於波爾值比較

//3. 驗證運算子(identity operators)

//swift 提供了兩個驗證運算子identity operators (=== 和 !==),用來檢驗兩個物件的指標是否指向同乙個例項變數

//4. 元組的比較

//兩個元組包含元素的個數和對應元素的型別相同才能比較,從左到右逐個比較,比較出第乙個後其餘的忽略

//元組比較只能用於比較小於七個元素的元組

(4, "dog") == (4, "dog") //true

//5. 三元運算子(ternary operators)

//和c語言一樣,swift只有乙個三元條件運算子 (a ? b : c)

//計算tableview 行高,如果有header, 行高比內容高度高50, 沒有高20

let contentheight = 40

let hasheader = true

let rowheight = contentheight + (hasheader ? 50 : 20)

//6. 空合運算子(nil-coalescing operator)

// a ?? b , a為可選型別

//如果a不為nil解包a的值返回,否則返回b。如果a非空,不會再評估b的值(短路評估short-circuit evaluation)

//相當於 a != nil ? a! : b

let defaultcolorname = "red"

var userdefinedcolorname: string? //userdefinedcolorname 為nil

var colornametouse = userdefinedcolorname ?? defaultcolorname // colornametouse值為red

//二. 區間運算子(range operators)

//1. 閉區間運算子(closed range operator)

//表達形式: a...b, 包含a, b, a 不能大於 b, 適用於for in迴圈

for index in 1...5

// 1 times 5 is 5

// 2 times 5 is 10

// 3 times 5 is 15

// 4 times 5 is 20

// 5 times 5 is 25

//2. 半開區間運算子(half-open range operator)

//表達形式: a..range.contains(7) //false

range.contains(4) //true

range.contains(-1) //true

//三.邏輯運算子(logical operators)

//與或非: !, &&,||

// a && b, a 為false,不再判斷b , 短路評估short-circuit evaluation

Swift 運算子過載和運算子函式

讓已有的運算子對自定義的類和結構進行運算或者重新定義已有運算子的運算規則,這種機制被稱為運算子過載。1,通過過載加號運算子,使自定義的兩個座標結構體物件實現相加 12 3456 78910 11structcenterpointer func left centerpointer,right cen...

Swift關係運算子和邏輯運算子

關係運算子是比較兩個表示式大小關係的運算,它的結果是true或false,即布林型資料。如果表示式成立 結果為true,為false。關係運算子有8種 和 以let a 6為例。具體說明參見表3 3。表3 3 關係運算子 運算子名稱 例子結果 等於a 4 false 不等於a 4 true 大於a ...

Swift 高階運算子

高階運算子 向上溢位 向下溢位 除零溢位,0作為被除數時結果是0 模零溢位,對 0求餘結果是0 varwilloverflow uint8 max 等於 255 willoverflow willoverflow 1 等於0 willoverflow willoverflow 1 等於2 varwi...