funchalfOpenRangeLength(start:Int,end:Int)->Int{returnend-start}println(halfOpenRangeLength(1,10))// prints "9"
Functions Without Parameters
12345
funcsayHelloWorld()->String{return"hello, world"}println(sayHelloWorld())// prints "hello, world"
Function Without Return Values
12345
funcsayGoodbye(personName:String){println("Goodbye, \(personName)!")}sayGoodbye("Dave")// prints "Goodbye, Dave!"
Functions with Multiple Return Values
12345678910111213141516
funcminMax(array:[Int])->(min:Int,max:Int){varcurrentMin=array[0]varcurrentMax=array[0]forvalueinarray[1..<array.count]{ifvalue<currentMin{currentMin=value}elseifvalue>currentMax{currentMax=value}}return(currentMin,currentMax)}letbounds=minMax([8,-6,2,109,3,71])println("min is \(bounds.min) and max is \(bounds.max)")// prints "min is -6 and max is 109"
Optional Tuple Return Types
123456789101112131415161718
funcminMax(array:[Int])->(min:Int,max:Int)?{ifarray.isEmpty{returnnil}varcurrentMin=array[0]varcurrentMax=array[0]forvalueinarray[1..<array.count]{ifvalue<currentMin{currentMin=value}elseifvalue>currentMax{currentMax=value}}return(currentMin,currentMax)}ifletbounds=minMax([8,-6,2,109,3,71]){println("min is \(bounds.min) and max is \(bounds.max)")}// prints "min is -6 and max is 109"
External parameter Names
123456789101112
funcsomeFunction(externalParameterNamelocalParameterName:Int){// function body goes here, and can use localParameterName// to refer to the argument value for that parameter}funcjoin(strings1:String,toStrings2:String,withJoinerjoiner:String)->String{returns1+joiner+s2}join(string:"hello",toString:"world",withJoiner:", ")// returns "hello, world"
Shorthand External Parameter Names
1234567891011
funccontainsCharacter(#string:String,#characterToFind:Character)->Bool{forcharacterinstring{ifcharacter==characterToFind{returntrue}}returnfalse}letcontainsAVee=containsCharacter(string:"aardvark",characterToFind:"v")// containsAVee equals true, because "aardvark" contains a "v"
// Note that Double... is different from [Double]funcarithmeticMean(numbers:Double...)->Double{vartotal:Double=0fornumberinnumbers{total+=number}returntotal/Double(numbers.count)}arithmeticMean(1,2,3,4,5)// returns 3.0, which is the arithmetic mean of these five numbersarithmeticMean(3,8.25,18.75)// returns 10.0, which is the arithmetic mean of these three numbers
Constant and Variable Parameters
123456789101112131415
funcalignRight(varstring:String,count:Int,pad:Character)->String{letamountToPad=count-countElements(string)ifamountToPad<1{returnstring}letpadString=String(pad)for_in1...amountToPad{string=padString+string}returnstring}letoriginalString="hello"letpaddedString=alignRight(originalString,10,"-")// paddedString is equal to "-----hello"// originalString is still equal to "hello"
In-Out Parameters
12345678910111213
// Variable parameters, as described above, can only be changed within the function itself. If you want a function to modify a parameter’s value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead.funcswapTwoInts(inouta:Int,inoutb:Int){lettemporaryA=aa=bb=temporaryA}varsomeInt=3varanotherInt=107swapTwoInts(&someInt,&anotherInt)println("someInt is now \(someInt), and anotherInt is now \(anotherInt)")// prints "someInt is now 107, and anotherInt is now 3"
Function Type
123456789101112131415
funcaddTwoInts(a:Int,b:Int)->Int{returna+b}funcmultiplyTwoInts(a:Int,b:Int)->Int{returna*b}varmathFunction:(Int,Int)->Int=addTwoIntsprintln("Result: \(mathFunction(2, 3))")// prints "Result: 5"mathFunction=multiplyTwoIntsprintln("Result: \(mathFunction(2, 3))")// prints "Result: 6"
Function Types as Parameter Types
12345
funcprintMathResult(mathFunction:(Int,Int)->Int,a:Int,b:Int){println("Result: \(mathFunction(a, b))")}printMathResult(addTwoInts,3,5)// prints "Result: 8"
Function Type as Return Types
1234567891011121314151617181920212223242526
funcstepForward(input:Int)->Int{returninput+1}funcstepBackward(input:Int)->Int{returninput-1}funcchooseStepFunction(backwards:Bool)->(Int)->Int{returnbackwards?stepBackward:stepForward}varcurrentValue=3letmoveNearerToZero=chooseStepFunction(currentValue>0)// moveNearerToZero now refers to the stepBackward() functionprintln("Counting to zero:")// Counting to zero:whilecurrentValue!=0{println("\(currentValue)... ")currentValue=moveNearerToZero(currentValue)}println("zero!")// 3...// 2...// 1...// zero!
Nested Functions
123456789101112131415161718
funcchooseStepFunction(backwards:Bool)->(Int)->Int{funcstepForward(input:Int)->Int{returninput+1}funcstepBackward(input:Int)->Int{returninput-1}returnbackwards?stepBackward:stepForward}varcurrentValue=-4letmoveNearerToZero=chooseStepFunction(currentValue>0)// moveNearerToZero now refers to the nested stepForward() functionwhilecurrentValue!=0{println("\(currentValue)... ")currentValue=moveNearerToZero(currentValue)}println("zero!")// -4...// -3...// -2...// -1...// zero!