Swift 函数(五)

前端之家收集整理的这篇文章主要介绍了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中的函数的参数和返回值可以定义的非常灵活,包括从只带一个未命名的简单函数到复杂的带有表达式参数名和不同参数选项的复合函数

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

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

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

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

3.函数参数名

函数的参数名只能在函数体内使用,称为局部参数名
    funcsomeFunction(parameterName:Int){
  1. //functionbodygoeshere,andcanuseparameterName
  2. //torefertotheargumentvalueforthatparameter
  3. }

4.外部参数名

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

5.简写外部参数名

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

6.默认参数

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

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

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

8.可变参数

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

9.常量参数和变量参数

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

10.输入输出参数

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

11.函数类型

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

12.使用函数类型

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

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

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

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

在返回箭头 (->) 后写一个完整的函数类型,表示将函数类型作为另一个函数的返回类型
    funcstepForward(input:Int)->Int{
  1. returninput+1
  2. funcstepBackward(input:Int)->Int{
  3. returninput-1
  4. funcchooseStepFunction(backwards:Bool)->(Int)->Int{
  5. returnbackwards?stepBackward:stepForward
  6. varcurrentValue=3
  7. letmoveNearerToZero=chooseStepFunction(currentValue>0)
  8. //moveNearerToZeronowreferstothestepBackward()function
  9. println("Countingtozero:")
  10. //Countingtozero:
  11. whilecurrentValue!=0{
  12. println("\(currentValue)...")
  13. currentValue=moveNearerToZero(currentValue)
  14. println("zero!")
  15. //3...
  16. //2...
  17. //1...
  18. //zero!

15.嵌套函数

定义在全局域中的称为全局函数,将函数定义在别的函数中,称为嵌套函数
    funcchooseStepFunction(backwards:Bool)->(Int)->Int{
  1. funcstepForward(input:Int)->Int{returninput+1}
  2. funcstepBackward(input:Int)->Int{returninput-1}
  3. varcurrentValue=-4
  4. //moveNearerToZeronowreferstothenestedstepForward()function
  5. whilecurrentValue!=0{
  6. println("\(currentValue)...")
  7. currentValue=moveNearerToZero(currentValue)
  8. println("zero!")
  9. //-4...
  10. //-3...
  11. //-2...
  12. //-1...
  13. //zero!
原文链接:https://www.f2er.com/swift/325176.html

猜你在找的Swift相关文章