博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
4.编写函数和闭包
阅读量:7200 次
发布时间:2019-06-29

本文共 5589 字,大约阅读时间需要 18 分钟。

hot3.png

##4.1函数 函数是有名称的闭包

//func funcName(paramName : type , ...) -> returnTypefunc fahrenheitToCelsius(fahrenheitValue : Double) -> Double {	var result : Double	result = (((fahrenheitValue - 32) * 5) / 9)		return result}

##4.2 调用函数

var outdoorInFahrenheit = 88.2var 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返回任意参数

//func funcName(paramName : type , ...) -> Any

##4.5无返回参数

//func funcName(paramName : type , ...) -> Viodfunc 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")

判断最大最小值

//largestfunc 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)//smallestfunc 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)

参考文章数学与数字// 无穷 ##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.将函数赋值给常量

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 = depositlet fridayTransaction = withdrawlet 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)")//CashcashBestCheck(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.5let 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

转载于:https://my.oschina.net/u/2319073/blog/841721

你可能感兴趣的文章