6.1. Writing functions
To write a function in Swift, we use the keyword func followed by the function's name, parameter list, return data type, and body (the code block). A general structure of a Swift function is:
func functionName(parameter1:DataType, parameter2:DataType, ...) -> ReturnDataType{
//code block
}Simple functions
For a function, the list of parameters can be empty, meaning if our function does not require any data from us to run, we do not need to define any parameters. For example, a function to print "Hello World" could be:
func printHelloWorld(){
print("Hello World!")
}You can call the function from your code like:
printHelloWorld()Last updated
Was this helpful?