# Swift Functions

> Learn how to declare functions in Swift with the func keyword, pass labeled parameters, return values, and use tuples to return more than one value.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2021-06-11 | Topics: [Swift](https://flaviocopes.com/tags/swift/) | Canonical: https://flaviocopes.com/swift-functions/

> This tutorial belongs to the [Swift](https://flaviocopes.com/swift-introduction/) series

Your program's code is organized into functions.

A function is declared using the `func` keyword:

```swift
func bark() {
    print("woof!")
}
```

Functions can be assigned to structures, classes and enumerations, and in this case we call them methods.

A function is invoked using its name:

```swift
bark()
```

A function can return a value:

```swift
func bark() -> String {
    print("woof!")
	  return "barked successfully"
}
```

And you can assign it to a variable:

```swift
let result = bark()
```

A function can accept parameters. Each parameter has a name, and a type:

```swift
func bark(times: Int) {
    for index in 0..<times {
        print("woof!")
    }
}
```

The name of a parameter is internal to the function.

We use the name of the parameter when we call the function, to pass in its value:

```swift
bark(times: 3)
```

When we call the function we must pass all the parameters defined.

Here is a function that accepts multiple parameters:

```swift
func bark(times: Int, repeatBark: Bool) {
    for index in 0..<times {
        if repeatBark == true {
            print("woof woof!")
        } else {
            print("woof!")
        }            
    }
}
```

In this case you call it in this way:

```swift
bark(times: 3, repeat: true)
```

When we talk about this function, we don't call it `bark()`. We call it `bark(times:repeat:)`.

This is because we can have multiple functions with the same name, but different set of parameters.

You can avoid using labels by using the `_` keyword:

```swift
func bark(_ times: Int, repeatBark: Bool) {
    //...the function body
}
```

So you can invoke it in this way:
```swift
bark(3, repeat: true)
```

It's common in Swift and iOS APIs to have the first parameter with no label, and the other parameters labeled.

It makes for a nice and expressive API, when you design the names of the function and the parameters nicely.

You can only return one value from a function. If you need to return multiple values, it's common to return a tuple:

```swift
func bark() -> (String, Int) {
    print("woof!")
	  return ("barked successfully", 1)
}
```

And you can assign the result to a tuple:

```swift
let (result, num) = bark()

print(result) //"barked successfully"
print(num) //1
```

Functions can be nested inside other functions. When this happens, the inner function is invisible to outside the outer function.
