Swift Function

Swift Function is a logical piece of code which represents a behaviour or functionality. A function can take arguments and can return a value.

Define a Function

To define a function in Swift, use func keyword; followed by function name; followed by the set of parameters that this function can accept, in parenthesis; followed by return type of the function, if any; and then the body of the function enclosed in flower braces.

The syntax of a function in Swift is

func functionName(parameterName1: Type, parameterName2: Type) -> ReturnType {
    //function body

where parameters and return type are optional.


In the following example, we will define a function greet, with no parameters and no return type. This function does print a message. After defining the function, we will call it using the function name greet.


func greet() {
    print("Hello World")



Now, let us modify greet(), such that is accepts a String for its parameter.


func greet(name: String) {
    print("Hello \(name)")

greet(name: "Abc")


Let us return the message from the function greet() and then print the returned String value.


func greet(name: String) -> String {
    return "Hello \(name)"

let value = greet(name: "Abc")


Swift Function Tutorials

The following tutorials cover some of the concepts or examples related to Swift Functions.



In this Swift Tutorial, we learned how to define a function in Swift, how to define parameters for a function, and how to specify the return type and return the value from function.