本文是學習《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