加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

函数类型

发布时间:2020-12-14 02:43:33 所属栏目:百科 来源:网络整理
导读://: Playground - noun: a place where people can play import UIKit // 每一个函数都有特定的函数类型 , 可以充当参数类型和函数的返回类型。 func addTwoInts(a: Int ,b: Int ) - Int { return a + b } func multiplyTwoInts(a: return a * b } // 使用函

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


import UIKit


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

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

return a + b

}

func multiplyTwoInts(a: return a * b

}

//使用函数类型

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

var mathFunction: (Int) -> Int = addTwoInts

mathFunction(2,4)

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

mathFunction = multiplyTwoInts

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

let anotherMathFunction = addTwoInts

anotherMathFunction(5,216)">7)

//函数类型的参数

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

func printMathResult(mathFun: ( Int,a: Int) {

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

}

printMathResult(addTwoInts,216)">10)

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

func stepForward(input: Int {

return input + 1

}

func stepBackward(input: return input - 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)

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读