Home
Search
Swift Func ExamplesUse funcs, specifying the var keyword to create local variables and return values.
Funcs. In Swift we specify funcs. With InOut we have output arguments—changes are retained at the caller. We can return tuples and optionals.
Extension note. An extension may add funcs to a class. Even a type like String or Int can have methods added with an extension block.
Extension
Initial example. Here we introduce a simple function: computeArea. It receives two arguments, the values "x" and "y." It returns an Int.
Return ComputeArea returns the product of the two parameters. The expression is computed and the value is returned.
Var We store the result of computeArea in a variable we declare with var. We then use print() to display it.
Var, Let
func computeArea(x: Int, y: Int) -> Int { return x * y } // Call the example func. var result = computeArea(10, y: 3) print(result)
30
External parameter names. A parameter can have two names in Swift. The first name specified is optional—this is an external parameter name.
Note An external parameter name is used when calling the func. It can make function calls more readable.
Here The "printMessage" func uses an external parameter name. We "print a message about" something.
func printMessage(about value: String) { // The identifier "about" is used for external labels. // The identifier "value" is used in the func. print("Your message is about \(value)") } // Test our external parameter name. printMessage(about: "Swift") printMessage(about: "turtles") printMessage(about: "cats")
Your message is about Swift Your message is about turtles Your message is about cats
Default parameters. A parameter can have a default value. We use an assignment expression in the formal parameter list. Here the value parameter is 100 when not specified in the caller.
func printValue(value: Int = 100) { // Write value to the console. print("Value is \(value)") } // The default parameter value is used. printValue() printValue(200)
Value is 100 Value is 200
Variable argument list. Sometimes we want a method that receives any number of arguments. This is a variadic func. We use an ellipsis to indicate a variadic method.
Then We can use the argument as an array in the method body. Here we use a for-in loop to iterate the array.
func sumStringLengths(values: String...) -> Int { // Loop over string array and sum String lengths. var sum = 0 for value in values { sum += value.characters.count } return sum } // Call the method with 2 arguments. let result = sumStringLengths("bird", "cat") print(result)
7
Constant arguments. In Swift, arguments are by default constant. We cannot reassign an argument in the func body. This helps prevent mistakes in coding.
Tip Please use the var keyword to have a non-constant argument. Or rewrite the method to use a local variable.
func printExample(argument: Int) { // This will not compile. argument = 10 } printExample(20)
main.swift:3:14: Cannot assign to 'let' value 'argument'
Static. This program uses a static func. We introduce the Music class, and provide a static play() method. Play() changes the static field named "count" when called.
Class
Note Static things are tied to types, not instances of those types. So only one "count" static field can exist in this program.
class Music { static var count = 0 static func play() { print("Music.play called: \(count)") // Increment static var. count++ } } // Call static method. Music.play() Music.play()
Music.play called: 0 Music.play called: 1
Inout. This keyword is used on a parameter. When modified, an inout parameter affects the variable at the calling location. One memory region is shared.
inout
Multiple return values. A func can return more than one value. We specify a tuple as its return value. Two or more values (of any type) can then be returned.
Tuple
Recursion. Sometimes a problem requires a search to be solved. With recursion, we can exhaustively search. We implement a recursive algorithm to count coins in Swift.
Recursion
A summary. A key part of a modern programming language is its function call syntax. In Swift we find powerful, new features like multiple return values and optional tuples.
Home
© 2007-2022 sam allen.
see site info on the changelog.