Functions are self-contained lumps of code that perform a particular task. You give functions a name which you want it to be identified with. Every function in Swift has a type, namely, a function’s parameter types and return type. Functions let us reuse specific code which performs the same specific tasks.
func favouritePerson() {print("My favourite is Hazeezah")}favouritePerson()
Let’s look at the code snippet above. To create a function in Swift, you have to start with func
.
favouritePerson
is the name of the function, as stated earlier, followed by a curly braces, with no parameter. The function is to print to the console.
Although it is correct, the reason nothing is printed is that we’ve placed the “My favorite is Fearless” message into a function called favoritePerson()
, and that code won’t be called until we ask Swift to run the favoritePerson()
function. You can run the code snippet below on your playground.
func favouritePerson(name: String) {print("My favourite person is \(name)")}favouritePerson(name: "Hazeezah")
From the code snippet above, to declare a function in Swift we need the work to acknowledge one esteem (called a “parameter”), named “title,” that ought to be a string. We at that point utilize string addition to type in that favorite collection title specifically into our yield message. To call the work, you compose this: favouritePerson(name: "Hazeezah")
Function parameters and return values are greatly adaptable in Swift. You’ll characterize anything from a basic utility work with a single anonymous parameter, to a complex work with expressive parameter names and diverse parameter options.
Functions can have numerous input parameters, which are composed inside the function’s enclosures, isolated by commas. This work takes a person’s title and whether they have as of now been welcomed as input, and returns a fitting welcome for that person:
func greet(name: String) -> String {return "hello, \(name)"}print(greet(name: "Waris!"))// Prints "Hello, Waris!"
Functions aren’t required to characterize a return sort. Here’s a adaptation of the greet(person:)
work, which prints its claim String esteem instead of returning it:
func greet(person: String) {print("Hello, \(person)!")}greet(person: "Waris")// Prints "Hello, Waris!"
Consider, for instance, we are announcing work values return sort as numbers. But what will happen when the work returns a string esteem or a nil
esteem? In that case, the compiler will return a blunder esteem. optional
is presented to urge freed of these problems.
Optional capacities will take two forms, value
and a nil
. We’ll specify Optionals
with the key saved character ?
to check whether the tuple is returning an esteem or a nil
esteem.
func subtractTwoNumber(_ a: Int, _ b: Int) -> Int {return a - b}func divideTwoNumber(_ a: Int, _ b: Int) -> Int {return a / b}print(subtractTwoNumber(5, 4))print(divideTwoNumber(20, 5))
The code snippet above defines two simple mathematical functions called subtractTwoNumbers
and divideTwoNumbers
. These functions each take two Int
values, and return an Int
value, which is the result of performing an appropriate mathematical operation.
The type of both of these functions is (Int
, Int
) -> Int
. This can be read as:
“A function that has two parameters, both of type Int, and that returns a value of type Int.”
If you need to characterize a work with a different number of contentions, at that point you can pronounce the individuals as variadic parameters. Parameters can be indicated as variadic by (···
) after the parameter title.
func divide(numbers: Int...) {for number in numbers {print("\(number) squared is \(number * number)")}}
All of the capacities you’ve experienced so far in this article have cases of worldwide capacities, which are defined at a worldwide scope. You’ll be able to characterize capacities inside the bodies of other capacities, known as settled or nested functions.
Nested capacities are covered up from the exterior world by default, but can still be called and utilized by their encasing work. An encasing work can moreover return one of its settled capacities to permit the settled work to be utilized in another scope.
All parameters passed into a functions are constants, so you cannot change them. But you can pass a parameter as an inout
.
func multiplyNumber(number: inout Int) {number *= 2}
There are several other things you can do with functions. You may have to go through Apple’s documentation on functions to see them and check out some other activities of functions.
At this point, I am sure you have been able to revise or update your knowledge on function type in Swift. Happy coding!