函数类型

//: Playground - noun: a place where people can play


import UIKit


//每一个函数都有特定的函数类型,可以充当参数类型和函数的返回类型。

func addTwoInts(a: Int, b: Int) -> Int {

    return a + b

}

func multiplyTwoInts(a: Int, b: Int) -> Int {

    return a * b

}

//使用函数类型

// swift 中您可以像任何其他类型一样的使用函数类型。例如,你可以定义一个常量或变量为一个函数类型,并指定适 当的函数给该变量:

var mathFunction: (Int, Int) -> Int = addTwoInts

mathFunction(2, 4)

//不同的函数相同的匹配类型可以分配给相同的变量,也同样的适用于非函数性类型:

mathFunction = multiplyTwoInts

mathFunction(2, 4)

//与其他类型一样,你可以把它迅速推断成函数类型当你为常量或变量分配一个函数时:

let anotherMathFunction = addTwoInts

anotherMathFunction(5,7)

//函数类型的参数

//您可以使用一个函数类型,(Int, Int)->Int 作为另一个函数的参数类型。

func printMathResult(mathFun: (Int, Int) -> Int, a: Int, b: Int) {

    println("Result:\(mathFun(a, b))")

}

printMathResult(addTwoInts, 5, 10)

//您可以使用一个函数类型作为另一个函数的返回类型。

func stepForward(input: Int) -> Int {

    return input + 1

}

func stepBackward(input: Int) -> Int {

    return input - 1

}

func chooseStepFunction(backwards: Bool) -> (Int)-> Int {

    return backwards ? stepBackward : stepForward

}

var currentValue = 3

let moveNearerToZero = chooseStepFunction(currentValue > 0)

//moveNearerToZero(9)

while currentValue != 0 {

    println("\(currentValue)")

    currentValue = moveNearerToZero(currentValue)

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值