Swift Functions

本文详细介绍了Swift语言中函数的定义与调用,包括参数传递、返回类型、多重返回值、可选元组返回、隐式返回、参数标签、默认参数值、变长参数、输入输出参数、函数类型及嵌套函数等高级特性。

Defining and Calling Functions

  • you can define one or more named, typed values that the function takes as input, known as parameters.
  • you can define one type that the function will pass back as output, known as return type.
func greet(person: String) -> String {
	return "hello " + person
}
print(greet(person: "Anna"))
print(greet(person: "Jack"))

Functions with Multiple Return Values

  • you can use a tuple type as the return type for a function to return multiple values
func getMinAndMax(array: [Int]) -> (min: Int, max: Int) {
	var min = array[0]
	var max = array[0]
	for number in array {
		if min > number {
			min = number
		} else if max < number {
			max = number
		}
	}
	return (min, max)
}
let (min, max) = getMinAndMax(array: [1, 2, -1, 0, -111])
let bound = getMinAndMax(array: [1, 2, -1, 0, -111])
print("min: \(min), max: \(max)")
print("min: \(bound.min), max: \(bound.max)")

note: the tuple’s members don’t need to be named at the point that the tuple is returned from the function, because their are already named when the function’s return type is defined

Optional Tuple Return type

  • if the tuple returned from the function can have no value, the return type can be defined as an optional tuple
func getMinAndMax(array: [Int]) -> (min: Int, max: Int)? {
	if array.isEmpty {
		return nil
	}
	var min = array[0]
	var max = array[0]
	for number in array {
		if min > number {
			min = number
		} else if max < number {
			max = number
		}
	}
	return (min, max)
}
  • you can use optional binding to check whether the function returns a value
if let bound = getMinAndMax(array: [0, 1, 2, -5, 10, 88]) {
	print("min: \(bound.min), max: \(bound.max)")
}

Functions with an Implicit Return

  • if the body of a function is a single expression, the function implicit returns that expression
func greet(person: String) -> String {
	"hello " + person + "!"
}

Function Argument Labels and Parameter Names

  • each function parameter has both an argument label and a parameter name
  • the argument label is used when the function is called. each argument is written in the function call with its argument label before it
  • the parameter name is used in the implementation of the function
  • by default, a parameter use its parameter name as argument label
func someFunction(firstParameterName: Int, secondParameterName: Int) {
    // In the function body, firstParameterName and secondParameterName
    // refer to the argument values for the first and second parameters.
}
someFunction(firstParameterName: 1, secondParameterName: 2)
  • parameter names are unique, but the argument labels can be same

Specifying Argument Labels

  • you can write a argument label before the parameter name, separated by a space
func someFunction(argumentLabel parameterName: Int) { }
func greet(person: String, from home: String) -> String {
	return "hello \(person) from \(home)"
}

Omitting Argument Labels

  • if you don’t want a argument label, write a underscore as a parameter’s argument label
func someFunction(_ parameter1: String, argumentLabel parameter2: String) { }
someFunction("aaa", argumentLabel: "bbb")

Default Parameter Value

  • you can define a default for a parameter value by assigning a value to the parameter in the function definition
func someFunction(withoutDefault: Int, withDefaultValue: Int = 10) { }

note: place the parameters that don’t have default value at the beginning of the parameter list, before the parameters that have default value

Variadic Parameters

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)
// returns 3.0, which is the arithmetic mean of these five numbers
arithmeticMean(3, 8.25, 18.75)
// returns 10.0, which is the arithmetic mean of these three numbers

In-Out Parameters

  • by default, function parameters are constants, that cannot be changed in the function.
  • you can define a parameter as in-out parameter to modify its value in the function.
  • define an in-out parameter by placing the inout keyword before the parameter’s type.
  • you can only pass a variable to an in-out parameter.
  • when you call the function and pass a variable to an in-out parameter, place an ampersand before the variable name.
func. swap(_ a: inout Int, _ b: inout Int) {
	var temp = a
	a = b
	b = a
}
var a = 10
var b = 20
swap(&a, &b)

Function Types

  • function types are made of the parameter types and the return type of the function
func. swap(_ a: inout Int, _ b: inout Int) {
	var temp = a
	a = b
	b = a
}
  • this function’s function type is (int, int) -> Void

Using Function Types

  • you can use function types like any other types in Swift.
var function: (Int, Int) -> Void = swap
var a = 1
var b = 2
function(&a, &b)

Function Types as Parameter Types

func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
    print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// Prints "Result: 8"

Function Types as Return Types

  • you can use a function type as another function’s return type.
func stepForward(_ input: Int) -> Int {
    return input + 1
}
func stepBackward(_ input: Int) -> Int {
    return input - 1
}
func chooseStepFunction(backword: Bool) -> (Int) -> Int {
	return backword ? stepBackword : stepForward
}

Nested Functions

  • you can define a function inside a function’s body, known as nested function.
  • nested function are hidden from the outside world, but can be called by its enclosing function.
  • an enclosing function can return its nested functions to allow them to be use in another scope.
func chooseStepFunction(backword: Bool) -> (Int) -> Int {
	func stepForward(input: Int) { return input + 1 }
	func stepBackward(input: Int) { return input - 1 }
	return backward ? stepBackward : stepForward
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值