1 //函数体内享有外部所有作用域 2 let global = "global" 3 func fn (args: String, args2: String) -> String { 4 print(global) 5 return args + "\t" + args2 6 } 7 8 var return_string: String = fn("string1", args2: "string3331"); 9 print(return_string) 10 11 12 13 14 15 //元组返回 16 func minMax(array: [Int]) -> (Int,Int)? { 17 if array.isEmpty { 18 return nil 19 } 20 var curren_min = array[0] 21 var curren_max = curren_min 22 //array[1..<2] 数组截取 23 for value in array[1..<array.count] { 24 if curren_min > value { 25 curren_min = value 26 }else if curren_max < value { 27 curren_max = value 28 } 29 } 30 return (curren_min, curren_max) 31 } 32 33 print(minMax([1,2,3,5,2,99,0])) 34 35 36 37 38 39 //外部参数名 40 41 func fnOutParams(in1 args1: String, in2 args2: String) { 42 print(args1 + " " + args2) 43 } 44 fnOutParams(in1: "aa", in2: "bb") 45 46 47 48 49 //省略外部参数名 50 51 func fnOutParams(args1: String, _ args2: String) { 52 print(args1 + " " + args2) 53 } 54 fnOutParams("aa", "bb") 55 56 57 58 59 //可变参数 60 61 func avgNumbers(numbers: Double...) -> Double { 62 var total: Double = 0 63 for number in numbers { 64 total += number 65 } 66 return total/Double(numbers.count) 67 } 68 print(avgNumbers(1,2,3,4,5.9,6,9,22)) 69 70 71 72 73 //参数重赋值(默认let 常量参数) 74 75 func reFn(var args: String) { 76 args = "cs"; 77 print(args) 78 } 79 reFn("reFn"); 80 81 82 83 84 //inout 指针传值 85 86 func swapVariable(inout args: String, inout _ args2: String) { 87 let tmp: String = args 88 args = args2 89 args2 = tmp 90 } 91 var a = "args1" 92 var b = "args2" 93 swapVariable(&a, &b) 94 print(a + "\t" + b) 95 96 97 98 99 100 // 函数类型 101 102 func addTwoInts(a: Int, _ b: Int) -> Int { 103 return a + b 104 } 105 func multiplyTwoInts(a: Int, _ b: Int) -> Int { 106 return a * b 107 } 108 109 let addTwoInts2 = addTwoInts; 110 print(addTwoInts2(1, 2)); 111 112 113 let variable_fn: (Int, Int) -> Int = multiplyTwoInts; 114 115 print(variable_fn(1, 2)); 116 117 118 119 120 121 122 //函数作为参数 123 124 func fnArgments(args: (Int, Int)-> Int, _ args2: Int, _ args3: Int) -> Int{ 125 return args(args2, args3) 126 } 127 128 print(fnArgments(addTwoInts2, 2, 3)) 129 130 131 132 133 134 //函数作为返回值 135 136 137 func fnRetruns(args: (Int, Int) -> Int) -> (Int, Int) -> Int{ 138 return args 139 } 140 141 let return_value = fnRetruns(multiplyTwoInts)(1, 5) 142 print(return_value); 143 144 145 146 147 //嵌套函数 148 149 func fnNesting(bool: Bool) -> (Int) -> Int{ 150 151 func stepForward(input: Int) -> Int { 152 return input + 1 153 } 154 155 func stepBackward(input: Int) -> Int { 156 return input - 1 157 } 158 159 return bool ? stepForward : stepBackward 160 } 161 162 print(fnNesting(true)(2))
时间: 2024-11-11 15:32:18