Swift5.1 函数笔记

import UIKit
var str = "Hello, playground"
func sayHelloWorld() -> String {
return "Hello , world"
}
func greet(person: String, alreadyGreeted: Bool) -> String{
return "hello, world"
}
func greet(person: String) {
print("hello,world")
}
func minMax(array: [Int]) -> (min: Int, max: Int)? {
guard !array.isEmpty else { return nil}
var currentMin = array[0]
var currentMax = array[0]
for value in array[1..<array.count] {
if value < currentMin {
currentMin = value
}else if value > currentMax{
currentMax = value
}
}
return (currentMax,currentMin)
}
if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) {
print("min is \(bounds.min) and max is \(bounds.max)")
}
func greeting(for person: String) -> String {
"Hello ," + person + "!"
}
print(greeting(for: "wei"))
func someFunction(argumentLabel parameterName: Int) {
}
func someFunction(_ firstParameterName: Int, secondParameterName: Int) {
}
func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
}
someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6)
someFunction(parameterWithoutDefault: 4)
func arithmeticMean(_ number: Double...) -> Double {
var total: Double = 0
for number in number {
total += number
}
return total / Double(number.count)
}
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
func addTwoInts(_ a: Int, _ b: Int) -> Int {
a + b
}
func multiplayTwoInts(_ a: Int, _ b: Int) -> Int {
a * b
}
var mathFunction: (Int, Int) -> Int = addTwoInts
print(mathFunction(2,3))
func printMathResult(_ mathFunction: (Int, Int) -> Int , _ a: Int , _ b: Int) {
print(mathFunction(a,b))
}
printMathResult(addTwoInts, 3, 5)
func stepForward(_ input: Int) -> Int {
print(3)
return input + 1
}
func setpBackward(_ input: Int) -> Int {
print(2)
return input - 1
}
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
print("1")
return backward ? setpBackward : stepForward
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
while currentValue != 0 {
print("\(currentValue)...")
currentValue = moveNearerToZero(currentValue)
}
print("Zero !")
func chooseStepFunctions(backward: Bool) -> (Int) -> Int {
func stepForward(input: Int) -> Int { return input + 1 }
func stepBackward(input: Int) -> Int { return input - 1 }
return backward ? stepBackward : stepForward
}
参考:
SwiftGG-函数
官方文档 Functions