HomeSearch

Swift Func Examples: Var, Return and Static

Use funcs. Specify the var keyword to create local variables and return values.

Funcs. A method does something. It computes the area of a circle. It calculates pi. In Swift we specify funcs with zero or more arguments and return values.

Func features. With InOut we have output arguments—changes are retained at the caller. We can return tuples and optionals. We can apply lambda expressions.

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
Swift program that uses func func computeArea(x: Int, y: Int) -> Int { return x * y } // Call the example func. var result = computeArea(10, y: 3) print(result) Output 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.

Swift program that uses external parameter name 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") Output 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.
Swift program that uses default parameter value func printValue(value: Int = 100) { // Write value to the console. print("Value is \(value)") } // The default parameter value is used. printValue() printValue(200) Output 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.

Swift program that uses variadic func 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) Output 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.

Swift program that causes error, assigns to argument func printExample(argument: Int) { // This will not compile. argument = 10 } printExample(20) Output 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.

Swift program that uses static method, var 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() Output 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

Extensions. An extension may add funcs to a class. Even a type like String or Int can have methods added with an extension block.Extension

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
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.