Swift高级开发语言--函数嵌套
发布时间:2020-12-14 01:42:36 所属栏目:百科 来源:网络整理
导读:// 函数嵌套:函数作用域中定义了另外一个函数,内层函数的作用域中可以使用外层函数的参数func helloLanou( var num : Int){ num++ func hello23(){ num++ } hello23() num}helloLanou( 10 )func hellolanou2 () - ((Int) - String) { func hanshu (i:Int) -
// 函数嵌套:函数作用域中定义了另外一个函数,内层函数的作用域中可以使用外层函数的参数
func helloLanou(var num: Int){
num++
func hello23(){
num++
}
hello23()
num
}
helloLanou(10)
func hellolanou2() -> ((Int) -> String) { func hanshu (i:Int) -> String
{
return "(i)"
}
return hanshu
}
hellolanou2()
let hanshu = hellolanou2()
let i = hanshu(1)
// 声明一个函数,实现功能:传入"+","-","*","/"的字符串,返回对应运算的函数:"+"-----返回int + int = int
func jjcc (str:String) -> ((Int,Int) -> Int)? { func jjcc1 (num1:Int,num2:Int) -> Int {
return num1 + num2
}
func jjcc2 (num1:Int,num2:Int) -> Int {
return num1 - num2
}
func jjcc3 (num1:Int,num2:Int) -> Int {
return num1 * num2
}
func jjcc4 (num1:Int,num2:Int) -> Int {
return num1 / num2
}
switch str {
case "+":
return jjcc1
case "-":
return jjcc2
case "*":
return jjcc3
case "/":
return jjcc4
default:
return nil
}
}
jjcc("+")
let func1 = jjcc("+")
let func2 = func1!(1,2)
// 函数的返回值是函数,可以用函数嵌套的形式实现,但是并不是必须使用函数嵌套
func func2(str:String) -> ((Int,Int) -> Int){ func resultFunc(num1:Int,num2:Int) -> Int{
switch str {
case "+":
return num1 + num2
case "-":
return num1 - num2
case "*":
return num1 * num2
case "/":
return num1 / num2
default:
return 0
}
}
return resultFunc
}
// 指定类型别名
typealias funcType = ((Int,Int) -> Int) func func3 () -> funcType {
func hanshu3 (num1:Int,num2:Int) -> Int {
return 0
}
return hanshu3
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |