##4.1函數 函數是有名稱的閉包swift
//func funcName(paramName : type , ...) -> returnType func fahrenheitToCelsius(fahrenheitValue : Double) -> Double { var result : Double result = (((fahrenheitValue - 32) * 5) / 9) return result }
##4.2 調用函數閉包
var outdoorInFahrenheit = 88.2 var outdoorInCelsius = fahrenheitToCelsius(fahrenheitValue: outdoorInFahrenheit)
##4.3其餘類型參數函數
func BulidASentence(subject : String ,choiceBool : Bool, Number : Double) -> String{ let boolString = String(choiceBool) let NumberString = String(Number) return subject + " " + boolString + " " + NumberString + "!" } var Asentence = BulidASentence(subject:"Swift",choiceBool:true,Number:10) BulidASentence(subject: "I", choiceBool: false, Number: 5)
##4.4返回任意參數rest
//func funcName(paramName : type , ...) -> Any
##4.5無返回參數code
//func funcName(paramName : type , ...) -> Viod func sayGoodbye(personName: String) { print("Goodbye, \(personName)!") } sayGoodbye(personName: "Zoujie")
##4.6可變參數對象
func addMyAccountBalances(blances : Double ... , name : String) -> Double{ var result : Double = 0 for blance in blances{ result += blance } return result } addMyAccountBalances(blances: 3.12,11.11,22.32, name: "Zoujie")
判斷最大最小值ip
//largest func findLargestBalance(blaces : Double ...) -> Double{ var result : Double = -Double.infinity // var result : Double = 0 print("\(result)") for blance in blaces{ if blance > result{ result = blance } } return result } findLargestBalance(blaces: -11.33,-22,11,-0.1) //smallest func findSmallestBalance(balances : Double ...) -> Double{ // var result : Double = Double.infinity 64位斷定數字大於1.797693134862315e+308 爲無窮大 var result : Double = 0 for blance in balances{ if (blance < result){ result = blance } } return result } findSmallestBalance(balances: -11.11,-111.11,-20)
參考文章數學與數字//http://swifter.tips/math-number/ 無窮 ##4.7默認參數 //賦值給參數,進行默認參數設置作用域
func writeCheck(payee : String = "Unknown" , amount : String = "10.00") -> String{ return "Check payable to " + payee + " for $" + amount } writeCheck()//"Check payable to Unknown for $10.00" writeCheck(payee: "Zoujie", amount: "11111111")//Check payable to Zoujie for $11111111"
##4.8函數是一級對象 1.將函數賦值給常量get
var account1 = ("State Bank Personl",1011.10) var account2 = ("State Bank Business",24309.63) func deposit(amount : Double, account :(name : String , balance : Double)) -> (String,Double){ let newBalance : Double = account.balance + amount return (account.name , newBalance) } func withdraw(amount : Double , account :(name : String , balance : Double)) -> (String , Double){ let newBalance : Double = account.balance - amount return (account.name , newBalance) } //函數賦值給常量 let mondayTransaction = deposit let fridayTransaction = withdraw let mondayBalance = mondayTransaction(300.00 , account1) //let mondayBalance = deposit(amount: 300.00, account: account1)等同上面 let fridayBalance = fridayTransaction(1200 , account2)
2.從函數返回函數數學
//返回的函數 (Double ,(String , Double)) ->(String , Double)即爲deposit或withdraw函數 func chooseTransaction(transaction : String) -> (Double , (String , Double)) ->(String , Double){ if transaction == "Deposit"{ return deposit//deposit 返回參數也爲(String , Double) } return withdraw } //1.返回函數賦值給常量 let myTransaction = chooseTransaction(transaction: "Deposit") myTransaction(110.01,account2) //2.直接調用返回函數 chooseTransaction(transaction: "Withdraw")(11.11,account1)
3.嵌套函數
func bankVault(passcode : String) -> String { //嵌套內函數,做用域只存在上層函數中,外部不可調用 func openBankVault() -> String{ return "Vault opened" } func CloseBankVault() -> String{ return "Vault closed" } if passcode == "secret" { return openBankVault() }else{ return CloseBankVault() } } print(bankVault(passcode: "secret")) print(bankVault(passcode: "wrongsecret"))
##4.9外部參數
func whiteBetterCheck(from payer : String , to payee : String ,total amount : Double) -> String{ return "Check payable from \(payer) to \(payee) for $\(amount)" } //from , to , total 做爲外部參數名 方便調用者查看 whiteBetterCheck(from: "Zoujie", to: "My wife", total: 1111111111)//"Check payable from Zoujie to My wife for $1111111111.0"
##4.10 inout參數 關鍵字inout告訴Swift,在函數內部可能修改這個參數的值,且這種修改必須反映到調用者處
func cashBestCheck(from : String , to : inout String , total : Double) -> String{ if to == "Cash"{ to = from } return "Check payable from \(from) to \(to) for $\(total) has been cashed" } var payer = "James Perry" var payee = "Cash" print("\(payee)")//Cash cashBestCheck(from: payer, to: &payee, total: 111.11)//"Check payable from James Perry to James Perry for $111.11 has been cashed" print("\(payee)")//"James Perry"
#4.2閉包 閉包與函數相似,就是一個代碼塊封裝了其所處環境的全部狀態,在閉包以前聲明的全部變量和常量都會被它捕獲
{(parameters) ->return_type in statements } let simpleInterestCalculationClosure = {(loanAmount : Double , interesRate : Double , years : Int) -> Double in var newinteresRate = interesRate / 100.0 var interest = Double(years) * newinteresRate * loanAmount//單利計算 return loanAmount + interest } func loadCalculator(loanAmount : Double , interestRate : Double , years : Int , calculator : (Double, Double,Int) ->Double) ->Double{ let totalPayout = calculator(loanAmount,interestRate,years) return totalPayout } var simple = loadCalculator(loanAmount: 10_000, interestRate: 3.875, years: 5, calculator: simpleInterestCalculationClosure)//11937.5 let compoundInterestCalculationClosure = {(loanAmount : Double , interestRate : Double , years : Int) -> Double in var newinterestRate = interestRate / 100.0 var compoundMultiplier = pow(1.0 + newinterestRate, Double(years))//pow求冪函數 return loanAmount * compoundMultiplier//複利計算 } var compound = loadCalculator(loanAmount: 10_000, interestRate: 3.875, years: 5, calculator: compoundInterestCalculationClosure)//12093.58841287692