funcminMax(array: [Int]) -> (min: Int, max: Int) { var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count] { if value < currentMin{ currentMin = value }elseif value > currentMax{ currentMax = value } } return (currentMin, currentMax) } print(minMax([18,20,12,54,87,32,21])) //输出(min: 12, max: 87)
funcminMax(array: [Int]) -> (min: Int, max: Int)? { if array.isEmpty { returnnil } var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count] { if value < currentMin{ currentMin = value }elseif value > currentMax{ currentMax = value } } return (currentMin, currentMax) }
//调用 let bounds = minMax(array: [32,55,87,12,46]) print("the max value of array is \(String(describing: bounds?.max))") //输出结果 the max value of array isOptional(87)
//greet函数 funcgreet(person: String,fromhometown: String) -> String { return"Hello \(person)! Glad you could visit from \(hometown)." }
//调用 print(greet(person: "Bill", from: "London"))
//输出:Hello Bill! Glad you could visit from London.
忽略参数标签
可以使用下划线来代替一个明确的参数标签
1 2 3 4 5 6 7
//实现 funcsomeFunction(_firstParameterName: Int, secondParameterName: String) { print("now I have used _ replace the parameter label") } //调用 someFunction(1, secondParameterName: "name")
funcswapTwoInts(aInta: inoutInt, bIntb: inoutInt) { let temp = a a = b b = temp } funcswapTwoDouble(a: inoutDouble, b: inoutDouble) { let temp = a a = b b = temp }
//调用 var someInt =3 var anotherInt =5 swapTwoInts(aInt: &someInt, bInt: &anotherInt) var someDouble =2.0 var anotherDouble =1.4 swapTwoDouble(a: &someDouble, b: &anotherDouble)