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 doSomethingWithAString(theString: String){   
    print(theString)
}
objectInstance.doSomethingWithAString("some string")

Method with 2 parameters, no return type

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

Alternate method declarations

The default state for Swift methods is for all parameters after the initial one 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.

Require initial parameter to be specified

In this declaration the initial parameter name must be specified when calling the method. This is specified using the # symbol in Swift 1.2, and by repeating the initial parameter name in Swift 2

//Swift 1.2
func doSomethingWith(#theString: String){
    print("Doing something with " + theString)
}
    
//Swift 2
func doSomethingWith(theString theString: String){
    print("Doing something with " + theString)
}
objectInstance.doSomethingWith(theString: "string")

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")

Hiding second (and 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 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)