本文已参与「新人创作礼」活动,一起开启掘金创作之路。
PART_A 控制流
-
for
-
for ... in
for index in 1 ... 5 { print(index) }
let names = ["cat", "dog", "fish"] for name in names { print(name) }
let nums = ["num1" : 1, "num2" : 2, "num3" : 3] for (num, count) in nums { print("\(num) is \(count)") } // 无序
-
普通for
for var x = 1(①); x <= 5(②); x++(④) { print(x)(③) } // 标注为执行顺序
-
-
while
-
普通while
var num = 1 while num <= 5 { print(num++) }
-
repeat ... while
var num = 1 repeat { print(num++) } while num <= 5
-
-
if
-
if
-
if ... else
-
if ... else if ... else
-
-
switch-case
-
每一个case后面必须包含语句,否则编译错误
-
case默认不用
break
来结束switch选择 -
case可用
,
来包含多个条件 -
case中可包含区间
...
、..<
、..>
-
case中可包含元组
case (_, 0)
,其中_
代表所有可能的值 -
case分支可进行值绑定:
case (let x, 0)
-
case中可用
where
语句来判断额外的条件:case let (x, y) where x == y
let today = "Monday" switch today { case "Monday": print("today is Monday") case "Tuesday": print("today is Tuesday") case "Wednesday": print("today is Wednesday") case "Thursday", "Friday": print("Don't put") default: print("404") } // today is Monday
-
-
控制转移语句
-
continue
:结束当前循环,进行下一次循环(如在for中) -
break
:直接跳至循环体结束}
-
fallthrough
:switch中如要贯穿就在case最后加上该句 -
带标签的语句
:labelName : while condition
,能明确多嵌套的循环体 -
guard
:提前退出 -
return
:结束/返回值 -
throw
:抛异常
-
-
检测 API 可用性
if #available(iOS 9, OSX 10.10, watchOS 9.7, *) { // } else { // }
PART_B 函数
-
函数定义与调用
-
定义
// func 函数名(参数名 : 参数类型) -> 返回值类型 func test(name : String) -> String { return "hello " + name }
-
调用:
print(test("catface"))
-
-
函数参数与返回值
-
无参:
func test() -> String
-
多参:
func test(str1 : String, falg : Bool) -> String
-
无返回值:
func test(str1 : String)
-
多重返回值:通过元组返回
-
可选元组返回类型:
func test(arr : [Int]) -> (min : Int, max : Int)?
func test(arr : [Int]) -> (min : Int, max : Int) { var currentMin = arr[0], currentMax = arr[0] for value in arr[0] ... arr.count { if value > currentMax { currentMax = value } else if value < currentMin { currentMin = value } } return (currentMin, currentMax) }
-
默认参数值:
func test(num : Int = 12)
-
可变参数(类似数组):
func test(nums : Double...) -> Double
-
常量参数和变量参数
-
函数参数默认是常量
-
变量参数仅存在于函数调用的生命周期中,仅能在函数体内被更改
func test(var str : String, totalLength : Int, pad : Character) -> String { let amountToPad = totalLength - str.characters.count if amountToPad < 1 { return str } let padStr = String(pad) for _ in 1 ... amountToPad { str += padStr } return str }
-
-
inout
:输入输出参数(如func change(inout a: Int, inout b: Int)
)-
修改后的参数值在函数调用结束后仍然存在
-
输入输出参数是函数对函数体外产生影响的另一种方式
-
-
-
函数类型
-
每个函数具有特定的函数类型
-
例1:
(Int, Int) -> Int
-
例2:
() -> Void
-
-
使用函数类型
var mathFunction: (Int, Int) -> Int = test
:此时两个函数功能相同
-
函数类型作为参数类型
func printMathResult(mathFunction: (Int, Int) -> Int, a: Int, b: Int)
-
函数类型作为返回类型
-
-
嵌套函数
-
嵌套函数对外界透明,但可被外围函数调用
-
外围函数可返回它的某个嵌套函数,使得该函数可在其他域中被使用
// 函数 func test(backwards: Bool) -> (Int) -> Int { func stepForward(input: Int) -> Int { return input + 1 } func stepBackward(input: Int) -> Int { return input - 1 } return backwards ? stepBackward : stepForward }
// 函数的调用 var flag = test(true) print(flag(3)) // 2
-