functions are reusable chunks of code to performa a particular task. Swift and Apple give us some funcs, but we can allso write our own.
methods - functions defined in a Type, including standard Types, and in Structs and Classes. Most Swift types have several of their own methods (e.g. the .append() method, available to any array).
- functions help to organize your code
- functions make it easy to reuse code
- functions make your programs smaller and more efficient
- and make your programs easier to maintain
You give a function a name that identifies what it does, and this name is used to “call” the function to perform its task when needed.
function without parameter
//Fuction definition
func functionName() {
//code
}
// Function call
functionName()function with parameter
func rollSidedDice(diceSides: Int) {
print("You rolled a \(Int.random(in: 1...diceSides)) on a \(diceSides) -sided dice.")
}
example
**import** UIKit
**func** rollSeveralDice(numberOfDice: Int, diceSides: Int) {
**guard** numberOfDice > 0 **else** {
print(" Cannot calculate roll of \(numberOfDice) dice")
**return**
}
**var** total = 0
**var** roll: Int
**var** totalString = ""
total = Int.random(in: 1...diceSides)
totalString = "\(total)"
**if** numberOfDice > 1 {
**for** _ **in** 2...numberOfDice {
roll = Int.random(in: 1...diceSides)
total = total + roll
totalString = totalString + ", \(roll)"
}
print(totalString)
print("Total roll: \(total)")
}
}
rollSeveralDice(numberOfDice: 0, diceSides: 8)function with return

one line functions dont need a return value

example switch case
