Swift Functions
A function is a set of statements that work together to achieve a certain goal. A function allows us to split our programme into smaller bits, making it more reusable and understandable.
There are two types of functions in Swift:
- User-defined Functions - We can write our own functions based on our needs.
- Standard Library Functions - These are built-in Swift functions that we can use in a program.
Declaring Swift Functions
We can declare a Swift function using the following syntax:
func function_name(parameters) -> return_type {
//code
return parameters//optional
}
Here, the keyword “func” is used to declare a function. We can assign any name to the function, “function_name” in this case. "returnType" indicates the type of value the function returns. The parameters are used to pass values to the function.
Example
//declaring a function
func swiftFunction() {
print("Swift function")
}
In this function, we have created a function named “swiftFunction” which displays the text “Swift function” in the output. There are no parameters or return types in this function. We will discuss the parameters and return types later.
Calling Swift Functions
In the above section, we saw how to declare a function in swift. Now, let’s learn how to call the function in a program. Suppose we have a function which will print “Hello” followed by the username provided as a parameter. Let’s see how we can call this function in the below example.
Code
//declaring a function and calling it
func sayHello(name: String) {
print("Hello \(name)")
}
//calling the function
sayHello(name: "John")
Here, we have passed the value of the parameter “name” as “John”. This will give the output as “Hello John”.
Output
Swift Function Parameters
In Swift language, the body of a function is accessed by giving its argument values. We can pass single or many argument values as tuples inside the function. In the below example, we have calculated the area of the circle by passing the parameter “radius” to the function “areaOfCircle.” This function is called inside a print statement to display the area of the circle returned by the function.
Code
//swift function with parameters to calculate the area of a circle
func areaOfCircle(radius: Double) -> Double {
return 3.14 * radius * radius
}
//calling the function
print(areaOfCircle(radius: 5))
Output
Swift Function Return Type
A Swift function can return a value using the return statement. We may want our function to return a value or function to have no return value at all.
Let’s see the below example to add two numbers which is returned by the “Int” return type in the swift function.
Code
//swift function to demonstrate return type
func add(a:Int, b:Int) -> Int {
return a + b
}
//call swift function
var result = add(a: 10, b: 20)
print(result)
In the above example, the function “add” takes two parameters of the “Int” type and returns the result as return type “Int.” We have called this function and stored the result in the variable “result.” Then the result is displayed using the print statement.
Output
Swift Nested Functions
All of the functions we have discussed till now in this article are global functions, meaning they are defined at the global level. Nested functions allow you to define functions within the bodies of other functions.
- The nested function is enclosed within the outer function and cannot be accessed by outside functions; attempting to do so will result in an error.
- Only their enclosed function can call them and use them.
The basic syntax of a nested function is as follows:
//swift syntax to demonstrate nested functions
func mainFunction() {
//code for mainFunction
func nestedFunction() {
//code for nestedFunction
}
//calling nestedFunction
nestedFunction()
}
Now, let’s look at an example to see how nested functions work in the Swift programming language.
Example
In the below example, the main function is named “mainFunc”, and the nested function inside it is called “nestedFunc.” The main and nested functions display a message when they are called. The important point here is that we can call the main function globally, but not the nested function. Look at the below example to have a clearer understanding of nested functions.
Code
//swift syntax to demonstrate nested functions
func mainFunc() {
//code for mainFunc
print("The main function\n")
//nested function code goes below
func nestedFunc() {
print("Nested function")
}
nestedFunc()
}
//call main function
mainFunc()
Output
Frequently Asked Questions
In Swift, do functions have types?
In Swift, every function has a type that contains the function's parameter types and return type. This type can be used in Swift like any other type, making it simple to give functions as parameters to other functions and to return functions from functions.
Is Swift an object-oriented language?
Swift has a lot of features that help you make object-oriented iOS apps. Object-oriented programming, on the other hand, is a broad topic.
Is Swift worth learning in 2022?
Swift. Apple created Swift to help developers create iOS apps. As the popularity of iOS applications grows around the world, it will remain one of the most in-demand languages in 2021. Swift is also an excellent language for mobile developers because it's simple to learn and supports practically everything Objective-C does.
Is Swift better than Python?
Swift and python performance differ; swift tends to be swifter and speedier than python. When choosing a programming language to learn, a developer should think about the job market and compensation. You can choose the best programming language by comparing all of these.
Conclusion
In this article, we have extensively discussed functions in the Swift programming language and the basics of the Swift language.
The key points covered in this post are:
- Overview of Swift
- Features
- Declaring Swift Functions
- Calling Swift Functions
- Swift Function Parameters
- Swift Function Return Type
- Swift Nested Functions
We hope that this blog has helped you enhance your knowledge of the Swift programming language. If you want to learn more, check out our articles on Swift Environment Setup, Apple Smart Glass Technology, Android Interview Questions, and Data Science Interview Questions. Do upvote our blog to help other ninjas grow.
Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, interview bundle, follow guided paths for placement preparations and much more.!
Happy Reading!