function function definition, parameter, return value
func sayHello(personName: String) -> String { let"Hello, ""!" return greeting}
Parameters and return values can be omitted
sayGoodbye(personName: String) { println("Goodbye, \(personName)!")}
can also contain multiple parameters and multiple return values
Func count (string1:String, string2:String) (Vowels:int, Consonants:int, Others:int) {varvowels =0, consonants =0, others =0 forCharacterinchstring1 {Switch String(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": ++consonantsdefault: ++others}}return(vowels, consonants, others)}
Multiple return values return a tuple, with no return value when it is actually returned void, an empty Ganso
Name of parameter
Parameter names can only be used internally by functions, but to make the language clearer, you define external parameter names that make your code easier to read by using these external parameter names
join(stringStringStringString-> String { return++ s2}join(string"hello""world"", ")
External names can be consistent with internal names
func containsCharacter(#stringString#characterToFind-> Bool { instring { if== characterToFind { returntrue } } returnfalse}let= containsCharacter(string"aardvark""v")
Function arguments can provide default values
FuncJoin(stringS1:String, toString S2:String, Withjoiner Joiner:String = " ") -String{returnS1+Joiner+S2}Join(string:"Hello"Tostring:"World")//returns "Hello World"Join(string:"Hello"Tostring:"World", Withjoiner:"-")//returns "Hello-world"
For parameters that provide default values, parameter names are automatically represented as internal and external names
Input and output parameters inout
, indicating that the parameters can be modified by the function body, and left to the external continue to use
a: Int, inout b: Int) { a a = b b = temporaryA}
The call needs to be added before the parameter&
var3var107swapTwoInts(&someInt, &anotherInt)
function type
The function type is determined by the parameter type and the return value type, which is similar to the C language function pointer
func addTwoInts(a: Int, b: Int) -> Int { return a + b}func multiplyTwoInts(a: Int, b: Int) -> Int { return a * b}varmathFunction(Int, Int) -> Int = addTwoIntsprintln("Result: \(mathFunction(2, 3))")mathFunction = multiplyTwoIntsprintln("Result: \(mathFunction(2, 3))")
The function type, like any other type, can be used as a parameter or as a return value.
func stepForward(input: Int) -> Int { return1}func stepBackward(input: Int) -> Int { return1}func chooseStepFunction(backwards: Bool) ->(Int) -> Int { return backwards ? stepBackward : stepForward}var3let0)
Functions can be nested
func chooseStepFunction(backwards: Bool) ->(Int) -> Int { func stepForward(input: Int) ->return1 } func stepBackward(input: Int) ->return1 } return backwards ? stepBackward : stepForward}
Closed Package
Closure features are applied in nested functions and closure expressions, and are a functional programming feature
Closed-Packet expression
The general form is as follows
(parameters) ->in statements}
For example
reversed = Sortedin return s1 > s2}) //closures can be type inferred, so it can be simplified to reversed = sorted (names, {s1, s2 in return s1 > s2}) //single-line expression can omit the returned return reversed = sorted (names, {s1, S2 in s1 > s2}) //You can also abbreviate parameters reversed = sorted (names, {$0 > $< Span class= "Hljs-number" >1 })
If the closure function is very long, in order to enhance readability, it can be said that the closure function is placed outside () immediately following the function call,
func someFunctionThatTakesAClosure(closure: () -> ()) { // 函数体部分}// 以下是使用尾随闭包进行函数调用someFunctionThatTakesAClosure() { // 闭包主体部分}
Capturing values
Closures can capture constants or variables in the context in which they are defined. Even though the original domain that defines these constants and variables does not already exist, closures can still reference and modify these values in the closure function body.
Func Makeincrementor (forincrement amount:int) () Int {varRunningTotal =0Func Incrementor () Int {runningtotal + = AmountreturnRunningTotal}returnIncrementor} LetIncrementbyten = Makeincrementor (forincrement:Ten) Incrementbyten ()//The value returned isTenIncrementbyten ()//The value returned is -Incrementbyten ()//The value returned is -
Getting started with Swift (ii)