Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Overview of Swift
2.1.
Features
2.2.
Syntax
3.
Swift Functions
3.1.
Declaring Swift Functions
3.1.1.
Example
3.2.
Calling Swift Functions
3.2.1.
Code
3.2.2.
Output
3.3.
Swift Function Parameters
3.3.1.
Code
3.3.2.
Output
3.4.
Swift Function Return Type
3.4.1.
Code
3.4.2.
Output
4.
Swift Nested Functions
4.1.
Example
4.1.1.
Code
4.1.2.
Output
5.
Frequently Asked Questions
5.1.
In Swift, do functions have types?
5.2.
Is Swift an object-oriented language?
5.3.
Is Swift worth learning in 2022?
5.4.
Is Swift better than Python?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Functions in Swift

Introduction

Swift is Apple's powerful and user-friendly programming language. It's used to develop applications for ios, macOS, and watchOS, among other platforms. 

In this article, we will understand the fundamentals of the Swift programming language from the ground up. We will start with the basics of the Swift language and learn defining and calling functions in the Swift language.

Let's get started with the basic concepts of the Swift programming language.

Overview of Swift

Chris Lattner created swift in July 2010 with the help of several other Apple programmers. Swift is the result of research on modern programming languages and decades of experience building Apple platforms. 
Swift is a beginner-friendly programming language. It's a high-performance programming language that's as expressive and pleasurable to use as a scripting language. Writing Swift code in a playground allows you to experiment with code and see the results right away without building and running an app.

Features

Various features of the Swift language are as follows:

(Diagram showing features of Swift Programming)

  1. Open Source
    Swift is maintained openly at Swift.org, with source code, a bug tracker, forums, and systematic development builds accessible to anyone.
  2. Package manager
    We can use the Swift package manager to build, run, test, and package Swift libraries and executables across platforms.
  3. Interoperability with Objective-C
    You can start building a new app using Swift today or use Swift code to add new features and functionality to your existing project. In the same project, Swift code coexists with your current Objective-C files.
  4. Memory safety
    Swift manages memory for you and prevents risky behaviour in your code.
  5. Compatibility of sources and binaries
    Swift has binary compatibility for apps in the most recent version. Every operating system release includes Swift libraries, ensuring that your apps use the most recent library version and that your code runs without the need to recompile.

Syntax

Swift is recognised for its easy-to-understand syntax. Let's go through some of the fundamentals of Swift syntax:

  1. Printing Hello World
    A Hello World programme in Swift is straightforward. We may do it in a single line, and no libraries or additional functionality are required.
//hello world program
print("Hello, World!")

2. Declaring a Variable
In Swift, you create variables with var and constants with let. Variables and constants must be of the same type as the value they will receive.

//declaring variables
var name = "John"
var age = 30
let isMale = true

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 SetupApple Smart Glass TechnologyAndroid 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!

Live masterclass