本文是学习《The Swift Programming Language》整理的相关随笔,基本的语法不作介绍,主要介绍Swift中的一些特性或者与OC差异点。
系列文章:
Defining and Calling Functions
这一节主要讲解Swift中的函数,Swift中函数的定义直接看一下官方例子一目了然。
例子:
func greet(person: String) -> String {
let greeting = "Hello, " + person + "!"
return greeting
}
print(greet(person: "Arnold"));
执行结果:
Hello, Arnold!
多返回值函数(Functions with Multiple Return Values)
You can use a tuple type as the return type for a function to return multiple values as part of one compound return
value.
- SWift中的函数的返回值可以是一个元组类型数据。
例子:
func minMax(array:[Int]) -> (min:Int,max:Int)?{
if array.isEmpty{
return nil;
}
var min = array[0];
var max = array[0];
for value in array[1..<array.count]{
if value < min{
min = value;
}else if value > max{
max = value;
}
}
return (min,max)
}
if let (min,max) = minMax(array: [2,5,3,1,6]){
print("min:\(min),max:\(max)");
}
执行结果:
min:1,max:6
注意可选型的使用,保证安全性
指定参数标签(Specifying Argument Labels)
You write an argument label before the parameter
name,separated by a space
- Swift的函数中可以在参数名的前面以空格隔开加入参数标签
例子:
func greet(person: String, from hometown: String) -> String {
return "Hello \(person)! Glad you could visit from \(hometown)."
}
print(greet(person: "Bill", from: "Cupertino"))
执行结果:
Hello Bill! Glad you could visit from Cupertino.
默认参数值(Default Parameter Values)
You can define a default value for any parameter in a
function by assigning a value to the parameter after that
parameter’s type. If a default value is defined, you can
omit that parameter when calling the function.
- 函数中的参数如果需要默认的值可以直接写在参数之后
func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
print("parameterWithoutDefault \(parameterWithoutDefault),parameterWithDefault \(parameterWithDefault)");
}
someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6);
someFunction(parameterWithoutDefault: 4);
执行结果:
parameterWithoutDefault 3,parameterWithDefault 6
parameterWithoutDefault 4,parameterWithDefault 12
可变参数(Variadic Parameters)
A variadic parameter accepts zero or more values of a
specified type. You use a variadic parameter to specify
that the parameter can be passed a varying number of input
values when the function is called. Write variadic
parameters by inserting three period characters (...)
after the parameter’s type name.
- Swift中引入了可变参数的概念,参数后加入
...
即可表示,该类型的数据可以传入0或者多个
例子:
func calculate(_ numbers: Double...) -> (Double){
var sum :Double = 0.0;
for var number in numbers{
sum += number;
}
return sum;
}
print("sum:\(calculate(1,2,3,4,5))");
执行结果:
sum:15.0
In-Out Parameters
Function parameters are constants by default. Trying to
change the value of a function parameter from within the
body of that function results in a compile-time error.
This means that you can’t change the value of a parameter
by mistake. If you want a function to modify a parameter’s value, and you want those changes to persist after the
function call has ended, define that parameter as an in-
out parameter instead.
- 函数的参数默认都是常量定义的,如果需要函数内部更改参数的值需要将参数用
inout
修饰
例子:
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}
var a:Int = 1;
var b:Int = 2;
swap(&a, &b);
print("a:\(a),b:\(b)");
执行结果:
a:2,b:1
函数作为参数(Function Types as Parameter Types)
You can use a function type such as (Int, Int) -> Int as a
parameter type for another function. This enables you to
leave some aspects of a function’s implementation for the
function’s caller to provide when the function is called.
例子:
func add(_ firstNum:Int,_ secondNum:Int) -> Int{
return firstNum + secondNum;
}
func minus(_ firstNum:Int,_ secondNum:Int) -> Int{
return firstNum - secondNum;
}
func calculate(_ calculateFunction:(Int,Int) -> Int,_ firstNum:Int,_ secondNum:Int) -> Int{
return calculateFunction(firstNum,secondNum);
}
print("add \(calculate(add,3,2))");
print("minus \(calculate(minus,3,2))");
执行结果:
add 5
minus 1
函数作为返回值(Function Types as Return Types)
You can use a function type as the return type of another
function. You do this by writing a complete function type
immediately after the return arrow (->) of the returning
function.
例子:
func add(_ firstNum:Int,_ secondNum:Int) -> Int{
return firstNum + secondNum;
}
func minus(_ firstNum:Int,_ secondNum:Int) -> Int{
return firstNum - secondNum;
}
func calculator(_ isAdd:Bool) -> (Int,Int) -> Int{
return isAdd ? add : minus;
}
var invokeCalculator = calculator(true);
print("add \(invokeCalculator(1,2))");
invokeCalculator = calculator(false);
print("minus \(invokeCalculator(3,2))");
执行结果:
add 3
minus 1
内嵌函数(Nested Functions)
直接看一个例子,把上一个例子中的addFunction
,minusFunction
放到calculator
中即可。
例子:
func calculator(_ isAdd:Bool) -> (Int,Int) -> Int{
func add(_ firstNum:Int,_ secondNum:Int) -> Int{
return firstNum + secondNum;
}
func minus(_ firstNum:Int,_ secondNum:Int) -> Int{
return firstNum - secondNum;
}
return isAdd ? addFunction : minusFunction;
}
var invokeCalculator = calculator(true);
print("add \(invokeCalculator(1,2))");
invokeCalculator = calculator(false);
print("minus \(invokeCalculator(3,2))");
执行结果:
add 3
minus 1