Swift Function函数

函数Function

1.无参数无返回值 

  • funcprintHelloWorld() {
  •     print("hello, world")
  • }

2.有参数无返回值

  • funcsayGoodbye(personName:String) {
  •     print("Goodbye,\(personName)!")
  • }
  • sayGoodbye("Dave")
  • // prints "Goodbye, Dave!"

3.一个参数

  • funcsayHello(personName:String) ->  String{
  •     letgreeting ="Hello, " +personName +"!"
  •     returngreeting
  • }
  • print(sayHello("Anna"))
  • // prints "Hello, Anna!"
  • print(sayHello("Brian"))
  • // prints "Hello, Brian!"

     函数名     参数名     参数类型    返回值类型

func sayHello(personName:String) ->  String 

4.多个参数

  • funcsayHello(personName:String,alreadyGreeted: Bool) -> String{
  •     ifalreadyGreeted {
  •         returnsayHelloAgain(personName)
  •     } else {
  •         returnsayHello(personName)
  •     }
  • }
  • print(sayHello("Tim",alreadyGreeted:true))
  • // prints "Hello again, Tim!"

上面的在函数的调用过程中,参数里面可以带参数名称的: alreadyGreeted:true

多参数之间使用”,”分开.

5.多值返回

  • funcminMax(array: [Int]) -> (min:Int,max: Int) {
  •     varcurrentMin =array[0]
  •     varcurrentMax =array[0]
  •     forvalueinarray[1..<array.count] {
  •         if value < currentMin {
  •             currentMin = value
  •         } else if value >currentMax {
  •             currentMax = value
  •         }
  •     }
  •     return (currentMin,currentMax)
  • }
  • letbounds =minMax([8, -6,2,109, 3, 71])
  • print("min is \(bounds.min) and max is\(bounds.max)")
  • // prints "min is -6 and max is 109"

6.可选元组返回

  • funcminMax(array: [Int]) -> (min:Int,max: Int)? {
  •     if array.isEmpty {returnnil }
  •     varcurrentMin =array[0
  •     varcurrentMax =array[0]
  •     forvalueinarray[1..<array.count] {
  •         if value < currentMin {
  •             currentMin = value
  •         } else if value >currentMax {
  •             currentMax = value
  •         }
  •     }
  •     return (currentMin,currentMax)
  • }
  • ifletbounds =minMax([8, -6,2,109, 3, 71]) {
  •     print("min is\(bounds.min) and max is\(bounds.max)")
  • }
  • // prints "min is -6 and max is 109"

和上面的多值返回相比 在函数{}前多了一个”?”.

7.指定外部参数名称

  • funcsayHello(toperson:String, and anotherPerson:String) ->String{
  •     return"Hello\(person) and\(anotherPerson)!"
  • }
  • print(sayHello(to:"Bill",and: "Ted"))
  • // prints "Hello Bill and Ted!"

8.省去外部参数名

  • funcsomeFunction(firstParameterName:Int,_ secondParameterName:Int) {
  •     // function body goes here
  •     // firstParameterName and secondParameterName refer to
  •     // the argument values for the first and second parameters
  •      print(“result is\(firstParameterName + secondParameterName)")
  • }
  • someFunction(1,2)

     // prints “result is 3”

9.带初始参数

  • funcsomeFunction(parameterWithDefault:Int = 12) {
  •     // function body goes here
  •     // if no arguments are passed to the function call,
  •     // value of parameterWithDefault is 12
    •          returnparameterWithDefault
  • }
  • someFunction(6)// parameterWithDefault is 6
  • someFunction()// parameterWithDefault is 12

10.不定参数个数

  • funcarithmeticMean(numbers:Double...) ->  Double {
  •     var total: Double = 0
  •     fornumberinnumbers {
  •         total += number
  •     }
  •     returntotal /Double(numbers.count)
  • }
  • arithmeticMean(1,2,3,4,5)
  • // returns 3.0, which is the arithmetic mean of these five numbers
  • arithmeticMean(3,8.25,18.75)
  • // returns 10.0, which is the arithmetic mean of these three numbers

11.常亮和变量参数

  • funcalignRight(varstring:String,totalLength:Int,pad:Character) ->  String{
  •     letamountToPad =totalLength -string.characters.count
  •     if amountToPad < 1 {
  •         return string
  •     }
  •     letpadString =String(pad)
  •     for _ in1...amountToPad {
  •         string =padString +string
  •     }
  •     return string
  • }
  • letoriginalString ="hello"
  • letpaddedString =alignRight(originalString,totalLength:10,pad:"-")
  • // paddedString is equal to "-----hello"
  • // originalString is still equal to "hello"

12.In-Out 参数

  • func swapTwoInts(inouta:Int, inout _ b Int) {
  •     lettemporaryA =a
  •     a = b
  •     b =temporaryA
  • }
  • varsomeInt =3
  • varanotherInt =107
  • swapTwoInts(&someInt, &anotherInt)
  • print("someInt is now\(someInt), and anotherInt is now\(anotherInt)")
  • // prints "someInt is now 107, and anotherInt is now 3"

in-out参数不能有初始默认值,inout参数不能是变量.上面的函数swapTwoInts

没有返回参数但是也完成了相似的功能.

13.函数赋值函数

  • funcaddTwoInts(a:Int, _ b:Int) ->  Int{
  •     return a + b
  • }

varmathFunction: (Int ,Int ) ->Int = addTwoInts

  • print("Result: \(mathFunction(2,3))")
  • // prints "Result: 5"

14.函数作为参数

  • funcprintMathResult(mathFunction: (Int Int ) -> Int,_a:Int , _b: Int) {
  •     print("Result:\(mathFunction(a,b))")
  • }
  • printMathResult(addTwoInts,3,5)
  • // prints "Result: 8"

15.函数作为返回值

  • funcstepForward(input:Int) ->  Int{
  •     return input + 1
  • }
  • funcstepBackward(input:Int) ->  Int{
  •     return input - 1
  • }
  • funcchooseStepFunction(backwards:Bool) -> ( Int) ->  Int{
  •     returnbackwards ?stepBackward :stepForward
  • }
  • varcurrentValue =3
  • letmoveNearerToZero =chooseStepFunction(currentValue >0)
  • // moveNearerToZero now refers to the stepBackward() function
原文地址:
https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html#//apple_ref/doc/uid/TP40014097-CH10-ID158

你可能感兴趣的:(函数,function)