Swift語言基礎筆記(四)

2021-07-23 19:27:26 字數 2154 閱讀 2187

通過前面幾篇的學習,swift的基礎型別學習的差不多了,接下來就學習流程控制與條件語句和運算子

一、運算子

//: playground - noun: a place where people can play

import uikit

//運算子swift學習,+ - * / % > < += -= || && | & 注意不同型別需要顯示強制轉換

var x = 10;

var y = 3;

var z = 0;

x/ydouble(x)/double(y);

var xx = +x;

var yy = -y;

x += 9;

if x > y

var capacity = 30;

var volume = 50;

if x > y && capacity < volume

if x < y || capacity > volumeelse

二、迴圈語句

迴圈語句有for、while、do-while

//: playground - noun: a place where people can play

import uikit

//迴圈語句有for、while、do-while

for index in -99...99

var i = -99;

for ; i <= 99 ;

for var a = -6.28; a <= 6.28; a += 0.1

var ii = -99;

var step = 1;

for ; ii <= 99; ii += step

var a = 10;

while a > 0

var awin = 0;

var bwin = 0;

var game = 0;

while awin < 3 && bwin < 3else if a < belse

}let winner = awin == 3 ? "a" : "b";

print("after \(game) games \(winner) win")

print("");

var aawin = false;

var bbwin = false;

var agame = 0;

repeatelse if a < belse

print("");

}while !aawin && !bbwin;

let awinner = aawin ? "a" : "b";

print("after \(awinner) win")

print("");

while true

let winner = a > b ? "a" : "b";

print("\(winner) win!");

break;

}

三、條件語句

switch if-else

//: playground - noun: a place where people can play

import uikit

//條件語句

var count = 15

if a > 20else

let rating = "a";

switch rating

let score = 100;

switch score

print("")

//x^4 - y^2 = 15* x * y;

findanswer:for m in 1...300

}}//where語句的使用

let point = (3, 5);

switch point

let age = 19;

switch age

if case 10...19 = age

if case 10...19 = age where age >= 18

let vector = (4, 0);

if case (let x, 0) = vector where x > 2 && x < 5

Swift語言學習筆記(四)

67.如果結構體 struct 的例項被宣告為常量的話,就不能對其屬性進行修改,即使是 var型別的屬性。而對於類 class 來說則不是這樣,如果乙個類的例項被宣告為常量,仍然可以修改其 var屬性。68.惰性屬性 lazy property 使用關鍵字 lazy 新增在宣告前面 惰性屬性在使用時...

swift 基礎筆記

常量與變數 常量用 let 關鍵字來宣告 變數用 var 關鍵字申明 變數設定後,可以改變值 常量設定後,無法改變 let name enda var old 21 可以一行申明多個 var t t e e let a a b b 可以設定型別 var hi string 整數 注視就是沒有小數部分...

Swift基礎(四) 閉包 列舉

目錄 1.閉包 閉包語法規則,閉包簡化,尾隨閉包,捕獲值,閉包是引用型別,非逃逸閉包,自動閉包 2.列舉 switch窮舉列舉,列舉關聯值,列舉的原始值,遞迴列舉 1.閉包 閉包的語法規則 var vararray aaaa gggg bbbb uuuu let varret vararray so...