您的位置:首页 > 移动开发 > Swift

swift——复合类型——函数——函数类型

2017-05-16 21:01 148 查看

函数类型

函数类型由参数类型和返回类型组成
func feed()
{
print("feed nothing")
}

func feed(rice: Int) -> Int
{
print("feed rice \(rice)")
return rice;
}

func feed(rice: Int, meat: Int) -> (Int, Int)
{
print("feed rice \(rice) and meat \(meat)")
return (rice, meat)
}

func use_functype()
{
let feed0: () -> Void = feed
let feed1: (Int) -> Int = feed
let feed2: (Int, Int) -> (Int, Int) = feed

feed0();
feed1(5)
feed2(5, 8)
}

output:
feed nothing
feed rice 5
feed rice 5 and meat 8

总结:
函数类型的返回类型本质为tuple,因此空tuple可用Void或()表示,但不可omit,只含单个成员tuple括号optional,包含多个成员tuple括号不可omit
函数类型的参数类型本质为tuple,因此空tuple可用Void或()表示,但不可omit,只含单个成员tuple括号optional,包含多个成员tuple括号不可omit
函数类型在使用上与普通类型(如Int)无任何区别,可使用let或var定义,亦可进行类型推断,只要不造成二义性error
函数名本质就是函数类型,只是常量(let)而已,函数定义时即进行了初始化,指向所定义函数

函数类型参数

func add(a: Int, _ b: Int) -> Int
{
return a + b
}

func sub(a: Int, _ b: Int) -> Int
{
return a - b
}

func arith(fun: (Int, Int) -> Int, _ a: Int, _ b: Int)
{
print("result: \(fun(a, b))")
}

func functype_param()
{
arith(add, 18, 8)
arith(sub, 18, 8)
}

output:
result: 26
result: 10

函数类型返回值

func add(a: Int, _ b: Int) -> Int
{
return a + b
}

func sub(a: Int, _ b: Int) -> Int
{
return a - b
}

func arith(flag: Bool) -> (Int, Int) -> Int
{
if(flag)
{
return add
}
else
{
return sub
}
}

func functype_ret()
{
let fun1 = arith(true)
let fun2 = arith(false)

print("result: \(fun1(18, 8))")
print("result: \(fun2(18, 8))")
}

output:
result: 26
result: 10

嵌套函数

func arith(flag: Bool) -> (Int, Int) -> Int
{
func add(a: Int, _ b: Int) -> Int
{
return a + b
}

func sub(a: Int, _ b: Int) -> Int
{
return a - b
}

if(flag)
{
return add
}
else
{
return sub
}
}

func nested_func()
{
let fun1 = arith(true)
let fun2 = arith(false)

print("result: \(fun1(18, 8))")
print("result: \(fun2(18, 8))")
}

output:
result: 26
result: 10
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息