Methods

This page shows how to declare and use methods in Swift

The examples assume that functions are declared in a class, and are being called from a separate class (in each case the instance of the class containing the methods is named objectInstance)

Method with no return type, no parameters

func doSomething() {
    print("Something has been done")    
}
objectInstance.doSomething()

Method with return type, no parameters

func doSomethingAndReturnABoolIndicatingSuccess() -> Bool {
    print("Something has been done")
    return true
}
var result = objectInstance.doSomethingAndReturnABoolIndicatingSuccess()

Method with one parameter, no return type

func doSomethingWith(aString: String){   
    print(theString)
}
objectInstance.doSomethingWith(aString: "some string")

Method with 2 parameters, no return type

func doSomethingWith(thisString: String, theNextString: String){
    print("Doing something with " + thisString + " and " + theNextString)
}
objectInstance.doSomethingWith(thisString: "s", theNextString: "b")

The above two methods show an example of method overloading

Alternate method declarations

The default state for Swift methods is for all parameters to be explicitly named in the method call, and for the name of the variable used in the method call to match that used in the methods implementation.

Developers are not required to maintain this format, and the examples below show how parameters can be explicitly named, omitted, or be given different names for the method call and method implementation.

Use different internal and external variable names

In this declaration the initial parameter name 'aString' is used in the method call, whereas the second 'theString' is used internally by the method's implementation

func doSomethingWith(aString theString: String){
    print("Doing something with: " + theString)
}
objectInstance.doSomethingWith(aString: "a string")

Omitting the initial parameter to be specified

In this declaration the initial parameter must be omitted when calling the method. This is specified by setting an the external parameter name as an underscore in Swift versions >2

func doSomethingWithAString(_ theString: String){
    print("Doing something with " + theString)
}
objectInstance.doSomethingWithAString("string")

Hiding subsequent variable names from the method call

If there is no benefit in the method call including second or subsequent variable names, we can omit them also by using an underscore as the external parameter name when declaring the method

func averageOfTwoInts(_ int1: Int, _ int2: Int) -> Int{
    return (int1 + int2) / 2
}
objectInstance.averageOfTwoInts(4, 8)