Swift7|Swift7 - 循环、函数

// for 循环 let names = ["Anna", "Alex", "Brian", "Jack"] for name in names { print("Hello, \(name)!") }let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4] for (animalName, legCount) in numberOfLegs { print("\(animalName)s have \(legCount) legs") }let base = 3 let power = 10 var answer = 1 for _ in 1...power { answer *= base } print("\(base) to the power of \(power) is \(answer)")// 半开区间运算符 ..< let minutes = 60 for tickMark in 0..

//返回值是元组 func minMax(array: [Int]) -> (min: Int, max: Int)? { if array.isEmpty { return nil } var currentMin = array[0] var currentMax = array[0]for value in array[1.. currentMax { currentMax = value } } return (currentMin, currentMax) }if let bounds = minMax(array: [8, -6, 2, 109, 3, 77]) { print("min is \(bounds.min) and max is \(bounds.max)") }//可变参数,一个函数最多只能拥有一个可变参数。 func arithmeticMean(_ numbers: Double...) -> Double { var total: Double = 0 for number in numbers { total += number } return total / Double(numbers.count) } arithmeticMean(1, 2, 3, 4, 5)//输入输出参数:函数可以修改参数的值,并且想要在这些修改在函数调用结束后仍然存在 func swaoTwoInts(_ a: inout Int, _ b: inout Int) { let temporaryA = a a = b b = temporaryA }var someInt = 3 var anotherInt = 104 swap(&someInt, &anotherInt) print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")//使用函数类型 func addTwoInts(_ a: Int, _ b: Int) -> Int { return a + b } func multiplyTwoInts(_ a: Int, _ b: Int) -> Int { return a * b } //”定义一个叫做 mathFunction 的变量,类型是‘一个有两个 Int 型的参数并返回一个 Int 型的值的函数’,并让这个新变量指向 addTwoInts 函数”。 var mathFunction: (Int, Int) -> Int = addTwoInts print("Result: \(mathFunction(2, 3))") mathFunction = multiplyTwoInts print("Result: \(mathFunction(2, 3))")func chooseStepFuntion(backward: Bool) -> (Int) -> Int { func stepForward(intput: Int) -> Int { return intput + 1 } func stepBackward(input: Int) -> Int { return input - 1 } return backward ? stepBackward : stepForward } var currentValue = https://www.it610.com/article/-4 let moveNearerToZero = chooseStepFuntion(backward: currentValue> 0) while currentValue != 0 { print("\(currentValue)...") currentValue = https://www.it610.com/article/moveNearerToZero(currentValue) } print("Zero!")

    推荐阅读