2015年8月10日 星期一

【Swift 筆記 Draft】第 5 講: Function


參數的Default值定義

定義 fun 時,可設定參數的 default 值。

fun payTicket(price:Int = 800)-> Int {
   return " Ticket price is \(price)"
}

payTicket()
payTicket(1200)


可變參數

函數的參數個數多少未知,但每個參數具有相同的 data type。運用時,可視這可變參數為一個數組。

fun dailyBooking(expenses:Int ...) -> Int {
   var totalExpense:Int = 0
   for expense in expenses {
     totalExpense += expense
   }
   return totalExpense
}

dailyBooking(10,20)
dailyBooking(10,20,30)


參數的傳值或傳址:

參數的傳值是 call by value,而傳址是 call by address。

傳值是呼叫者 copy 相同的值,讓被呼叫的函式 function 使用。兩者各占記憶體 RAM。

傳址是呼叫者將其值得 address,讓被呼叫的函式 function 參考,兩者都參考到相同、且唯一的記憶體 RAM。 

參數的 data type 被宣告為類別 class 時,其呼叫 function 時是傳址 call by address,其他如宣告為整數型、浮點 floating point 、布爾 boolean 、字串 string、元組 tuples、集合 array / dictionary、列舉 enumeration 、結構 struct 等都是傳值 call by value。但,後者可強制使用 inout 這修飾 keyword,命令其只傳址,不過在呼叫時,要在變數前加上位址符號 &。

fun swap(inout x:Int, inout y:Int) {
   var temp:Int
   temp = x
   x = y
   y = temp
}

var num1 = 10, num2 = 20
swap(&num1, &num2)
println("num1: \(num1), num2:\(num2)")

函式的返回值 Return Value:

無返回值

1. fun name(parameters) { ... }  // 無返回值
2. fun name(parameters) -> () { ... }  //返回空的 tuples
3. fun name(parameters) -> Void { ... } //返回Void的類型
返回多個數值

沒有留言:

張貼留言

prettyPrint();