微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift 函数(五)

函数 Functions

1.定义与调用

用func作为前缀来标志这是一个函数,用 (->) 加返回类型的名字表示该函数返回什么类型
[objc] view plain copy
  1. funcsayHelloAgain(personName:String)->String{
  2. return"Helloagain,"+personName+"!"
  3. }
  4. println(sayHelloAgain("Anna"))
  5. //prints"Helloagain,Anna!"

2.参数与返回值

Swift中的函数的参数和返回值可以定义的非常灵活,包括从只带一个未命名的简单函数到复杂的带有表达式参数名和不同参数选项的复合函数

多个参数,写在圆括号中,用逗号分隔
@H_502_75@ funchalfOpenRangeLength(start:Int,end:Int)->Int{
  • returnend-start
  • println(halfOpenRangeLength(1,10))
  • //prints"9"

  • 无参 ,尽管没有参数,圆括号也不能省略,调用的时候也是函数名加圆括号
    @H_502_75@ funcsayHelloWorld()->String{
  • return"hello,world"
  • println(sayHelloWorld())
  • //prints"hello,world"

  • 无返回值
    没有返回值就没有返回箭头和返回类型
    @H_502_75@ funcsayGoodbye(personName:String){
  • println("Goodbye,\(personName)!")
  • sayGoodbye("Dave")
  • //prints"Goodbye,Dave!"

  • 多返回值
    元组来让多个值作为一个复合值从函数中返回
    @H_502_75@ funccount(string:String)->(vowels:Int,0); background-color:inherit">consonants:Int,0); background-color:inherit">others:Int){
  • varvowels=0,consonants=0,others=0
  • forcharacterinstring{
  • switchString(character).lowercaseString{
  • case"a","e","i","o","u":
  • ++vowels
  • case"b","c","d","f","g","h","j","k","l","m",
  • "n","p","q","r","s","t","v","w","x","y","z":
  • ++consonants
  • default:
  • ++others
  • }
  • return(vowels,consonants,others)
  • lettotal=count("somearbitrarystring!")
  • println("\(total.vowels)vowelsand\(total.consonants)consonants")
  • //prints"6vowelsand13consonants"

  • 3.函数参数名

    函数的参数名只能在函数体内使用,称为局部参数名
    @H_502_75@ funcsomeFunction(parameterName:Int){
  • //functionbodygoeshere,andcanuseparameterName
  • //torefertotheargumentvalueforthatparameter
  • }
  • 4.外部参数名

    如果希望在函数调用的时候使用函数提供的参数的名字,就需要再定义一个外部参数名,写在局部参数名之前,空格分开
    @H_502_75@ funcsomeFunction(externalParameterNamelocalParameterName:Int){
  • arameterName
  • }
  • 以下是不使用和使用外部参数名的例子,其实代码执行是一样的,但是有了外部参数名,能让人比较直观的了解代码是要干什么的,增加可读性
    @H_502_75@ funcjoin(s1:String,0); background-color:inherit">s2:String,0); background-color:inherit">joiner:String)->String{
  • returns1+joiner+s2
  • join("hello","world",",")
  • //returns"hello,world"
  • funcjoin(strings1:String,toString join(string:"hello",0); background-color:inherit">toString:"world",0); background-color:inherit">withJoiner:",world"

  • 5.简写外部参数名

    上一个的简写方式,在参数名前加(#),告诉Swfit这个参数既作为外部参数,也作为局部参数
    @H_502_75@ funccontainsCharacter(#string:String,#characterToFind:Character)->Bool{
  • forcharacterinstring{
  • ifcharacter==characterToFind{
  • returntrue
  • false
  • letcontainsAVee=containsCharacter(string:"aardvark",0); background-color:inherit">characterToFind:"v")
  • //containsAVeeequalstrue,because"aardvark"containsa"v"

  • 6.默认参数

    在函数定义的时候为每个参数定义默认值,当函数调用的时候可以略去这个参数
    @H_502_75@ funcjoin(string withJoinerjoiner:String="")->String{
  • returns1+joiner+s2
  • join(string:"hello",0); background-color:inherit">withJoiner:"-")
  • //returns"hello-world"
  • toString:"world")
  • //returns"helloworld"

  • 7.默认参数的外部参数名

    给默认参数起一个默认外部参数名是比较常用的,保证了当函数被调用且带有默认值的参数被使用时,代码更清晰,如果你没有给带有默认值的参数提供外部参数名的话,Swift会自动提供的,此时外部参数和局部参数名是一样的,就像自动被加了 (#) 号
      joiner:String="")->String{
    1. joiner:"-")
    2. //returns"hello-world"

    8.可变参数

    函数调用时,如果不确定参数的数量,通过在变量类型后面加 (...) 定义可变参数,一个函数最多能有一个可变参数,且必须是函数表中最后的一个,避免函数调用时出现歧义,所以一个函数如果有一个或多个带默认值的参数,还有一个可变参数,千万把可变参数放在最后
    @H_502_75@ funcarithmeticmean(numbers:Double...)->Double{
  • vartotal:Double=0
  • fornumberinnumbers{
  • total+=number
  • returntotal/Double(numbers.count)
  • arithmeticmean(1,2,3,4,5)
  • //returns3.0,whichisthearithmeticmeanofthesefivenumbers
  • arithmeticmean(3,8,19)
  • //returns10.0,whichisthearithmeticmeanofthesethreenumbers

  • 9.常量参数和变量参数

    函数参数默认都是常量,想在函数体内更改参数值将会报错,但有时候,会在函数中有传入参数的变量值副本,通过指定一个或多个参数作为变量参数参数,从而避免在函数中定义新的变量,通过在参数名前加var来定义变量参数
    @H_502_75@ funcalignRight(varstring:String,0); background-color:inherit">count:Int,0); background-color:inherit">pad:Character)->String{
  • letamountToPad=count-countElements(string)
  • for_in1...amountToPad{
  • string=pad+string
  • returnstring
  • letoriginalString="hello"
  • letpaddedString=alignRight(originalString,10,"-")
  • //paddedStringisequalto"-----hello"
  • //originalStringisstillequalto"hello"
  • alignRight函数将参数string定义为变量参数,意味着string作为一个局部变量,用传入的字符串值初始化,并在函数体中进行操作,但也仅仅存在于函数调用的生命周期内

    10.输入输出参数

    如果想要一个函数可以修改参数的值,并且这些修改在函数结束调用后仍然存在,那就可以定义为输入输出参数,在参数前面添加inout关键字,这个值被函数修改后被传出函数,并替换原来的值,同时,传入的只能是变量而不能是常量,当传入的参数作为作为输入输出参数时,需要在参数面前加 & 符号,表示这个值可以被修改
    @H_502_75@ funcswapTwoInts(inouta:Int,inoutb:Int){
  • lettemporaryA=a
  • a=b
  • b=temporaryA
  • varsomeInt=3
  • varanotherInt=107
  • swapTwoInts(&someInt,&anotherInt)
  • println("someIntisNow\(someInt),andanotherIntisNow\(anotherInt)")
  • //prints"someIntisNow107,andanotherIntisNow3"

  • 11.函数类型

    每个函数都有特定的函数类型,由参数类型和返回类型组成
    @H_502_75@ funcaddTwoInts(a:Int,0); background-color:inherit">b:Int)->Int{
  • returna+b
  • funcmultiplyTwoInts(a:Int,b:Int)->Int{
  • a*b
  • //以上两个的函数类型是(Int,Int)->Int
  • funcprintHelloWorld(){
  • println("hello,world")
  • //这个函数类型是()->()

  • 12.使用函数类型

    使用函数类型就跟使用其他类型一样,比如可以定义一个常量或变量,类型就是函数,而且可以给这个函数赋值
    以下定义一个mathFunction的变量,类型是 两个int型参数并返回int型的函数,并让这个变量指向addTwoInts函数
    @H_502_75@ varmathFunction:(Int,Int)->Int=addTwoInts
  • println("Result:\(mathFunction(2,3))")
  • //prints"Result:5"
  • 有相同参数类型且返回类型相同的不同函数可以赋值给同一个变量
    @H_502_75@ mathFunction=multiplyTwoInts
  • //prints"Result:6"
  • 在赋一个函数给常量或变量时,可以省略函数类型
    @H_502_75@ letanotherMathFunction=addTwoInts
  • //anotherMathFunctionisinferredtobeoftype(Int,Int)->Int

  • 13.函数类型作为参数类型

    用 (Int,Int) -> Int 这样的函数类型作为另一个函数的参数,将函数的一部分实现交给函数的调用者
    @H_502_75@ funcprintMathResult(mathFunction:(Int,Int)->Int,248)"> println("Result:\(mathFunction(a,b))")
  • printMathResult(addTwoInts,3,0); background-color:inherit">//prints"Result:8"

  • 14.函数类型作为返回类型

    在返回箭头 (->) 后写一个完整的函数类型,表示将函数类型作为另一个函数的返回类型
    @H_502_75@ funcstepForward(input:Int)->Int{
  • returninput+1
  • funcstepBackward(input:Int)->Int{
  • returninput-1
  • funcchooseStepFunction(backwards:Bool)->(Int)->Int{
  • returnbackwards?stepBackward:stepForward
  • varcurrentValue=3
  • letmoveNearerToZero=chooseStepFunction(currentValue>0)
  • //moveNearerToZeroNowreferstothestepBackward()function
  • println("Countingtozero:")
  • //Countingtozero:
  • whilecurrentValue!=0{
  • println("\(currentValue)...")
  • currentValue=moveNearerToZero(currentValue)
  • println("zero!")
  • //3...
  • //2...
  • //1...
  • //zero!

  • 15.嵌套函数

    定义在全局域中的称为全局函数,将函数定义在别的函数中,称为嵌套函数
    @H_502_75@ funcchooseStepFunction(backwards:Bool)->(Int)->Int{
  • funcstepForward(input:Int)->Int{returninput+1}
  • funcstepBackward(input:Int)->Int{returninput-1}
  • varcurrentValue=-4
  • //moveNearerToZeroNowreferstothenestedstepForward()function
  • whilecurrentValue!=0{
  • println("\(currentValue)...")
  • currentValue=moveNearerToZero(currentValue)
  • println("zero!")
  • //-4...
  • //-3...
  • //-2...
  • //-1...
  • //zero!
  • 版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

    相关推荐