Looking for swift Answers? Try Ask4KnowledgeBase
Looking for swift Keywords? Try Ask4Keywords

Swift Language Functions with Parameters


Example

Functions can take parameters so that their functionality can be modified. Parameters are given as a comma separated list with their types and names defined.

func magicNumber(number1: Int)
{
    print("\(number1) Is the magic number")
}

Note: The \(number1) syntax is basic String Interpolation and is used to insert the integer into the String.

Functions with parameters are called by specifying the function by name and supplying an input value of the type used in the function declaration.

magicNumber(5)
//output: "5 Is the magic number
let example: Int = 10
magicNumber(example)
//output: "10 Is the magic number"

Any value of type Int could have been used.

func magicNumber(number1: Int, number2: Int)
{
    print("\(number1 + number2) Is the magic number")
}

When a function uses multiple parameters the name of the first parameter is not required for the first but is on subsequent parameters.

let ten: Int = 10
let five: Int = 5
magicNumber(ten,number2: five)
//output: "15 Is the magic number"

Use external parameter names to make function calls more readable.

func magicNumber(one number1: Int, two number2: Int)
{
    print("\(number1 + number2) Is the magic number")
}

let ten: Int = 10
let five: Int = 5
magicNumber(one: ten, two: five)

Setting the default value in the function declaration allows you to call the function without giving any input values.

func magicNumber(one number1: Int = 5, two number2: Int = 10)
{
    print("\(number1 + number2) Is the magic number")
}

magicNumber()
//output: "15 Is the magic number"