In Swift, a function can be declared using the func
keyword followed by the name of the function, a set of parentheses that may include parameters, and an optional return type.
Here is an example of a function that takes two parameters of type Int
and returns their sum:
main.swift64 chars4 lines
In this example, the function is named addNumbers
, takes two parameters of type Int
, and returns an Int
.
The ->
symbol is used to specify the return type of the function. In this case, the function returns an Int
.
To call the function, you can simply use its name and pass in the required arguments:
main.swift85 chars3 lines
In this example, the addNumbers
function is called with arguments 5
and 7
, which returns the value 12
. This value is then assigned to the constant result
and printed to the console.
gistlibby LogSnag