Functions in Swift

swift May 01, 2022
Functions in Swift

The function is a set of commands/statements. To create a simple function, you first have to define and name it; generally, naming is according to the task you want it to perform. For example:

var age = 18
let name = "Krishna"
print("Hi, I am " + "\(name)")
print("I am " + "\(age)")

The set of commands you see above may be needed more than once for the XYZ project, and programmers make work easy for people, including them. To use the same code every time, the concept of function is essential.

Also, functions are like your school notes. You write down the notes given by your instructor, but when referring to it, you look through the problems and do not entirely solve them again. So functions reference your code every time you need them; initialize it.

Declaring and Calling Functions

Declaring a function and writing the code inside parenthesis will work precisely. The exciting thing is that you don't have to write many lines of code again now and then in the future. Call the function as shown in the example below, and it will perform it.

func myInfo() {
  var age = 18
  let name = "Krishna"
  var line = ("Hi, I am " + "\(name) \n") + ("I am " + "\(age)")


If you see, it now looks better and structured. Just like "var" and "let" keywords, we have a "func" keyword for declaring a function. Then name the function like how
you call your variables and constants but add open and close braces and end up with open and close parenthesis.

func car() {
	/* lines of code */

The function will never run automatically. To run a function, you need to call it whenever you wish to run it. Calling a function is simple, write "car()" and then whatever code is inside this function, the console will try running that.



You learned how to write a function and call it. But what if you want the other name instead of "Joey" or "Chandler" or "Xyz" every time?
The answer is to use parameters in a function. The parameters help get new values every time you try calling a function.

You can see a parameter "product" with a type String in the example below. Just like you assign a new value to a variable, you give a value to your function, which eventually helps replace that value everywhere you use that parameter in the code written inside the parenthesis of a function.

func appleProduct(product: String) {
//               ----------------- 
//                       ∣
//                  (Parameter)
  print("\(product)" + " is an Apple product")

appleProduct(product: "iPhone 13")

//Example 2 with two Parameters

func tesla(model: String, year: Int) {
//        ------------------------- 
//                   ∣
//               (Parameter)
  print("Tesla" + " \(model)" + " was released in the year" + " \(year)")

tesla(model: "Roadster", year: 2018)

Return Values

"Return" in programming means returning a value. The function receives the value from what you entered, but it can also return the value by giving it back to you.

For example,

func circleArea(radius: Double) -> Double {

    let pi = 3.14
    var formula = pi*radius*radius
    return formula

let answer = circleArea(radius: 3.5)

Note: Return is similar to the print statement, but they are not the same. When you return a value and then call a function, it won't print any value. You must declare a variable or a constant and then print it with its help!

So to return a value, add "->" after the parameters list and when returning a value, write the keyword "return" just before your closing bracket of a function.

Argument Labels

Until now, you only understood the overview concept of parameters, but when you name a parameter, it serves/assigns the same label to the argument, and the parameter name itself is known as "argument labels" and "parameter names".

By default, the parameters use their parameter names as their argument labels.

In simple terms, think like the x variable when you were in high school and solving some algebraic problems. When the coefficient of x is 1, you don't write 1x but x. During the time, you ignored writing 1 before your variable because it wasn't needed; just like that, with simple parameters in use in your function, you don't have to bother much about argument labels.
Though you write a coefficient before the variable when it is greater than the value 1 because you can't just make it an assumption because it would make it intricate/complex to understand the problem, about the same, argument labels make your program readable and ease for you and other team members.

Now your question could be:
What's the position of the argument label in a function syntax?

To simply answer it, the argument labels are just written before the parameter names and leave a space in between.

func marvel(year: Int, spiderman movie: String) {
//                     --------- -----
//                         |       |
//              (Argument Label) (Parameter Name)

    print("\(movie) was released in \(year)")

marvel(year: 2021, spiderman: "Spider-Man: No Way Home")

In the above example, you must have noticed that when you call the function marvel, you will write an argument label inside the round braces for the second parameter and not a parameter name, but that's the opposite when using it in a print statement.

Another important thing you must have guessed is that the first parameter of this function will be used as a parameter name and argument label.

Excluding Argument Labels

You can drop giving the name to an argument label by replacing it with a "_" (underscore). For example,

func marvel(_ year: Int, spiderman movie: String) {

    print("\(movie) was released in \(year)")

marvel(2021, spiderman: "No Way Home")

If you use an argument label in your parameter, be careful to label it.

Default Parameter Values

Try remembering how you assigned a value to a variable at a time of declaring,

var x = 3

Declaring/assigning a value to a parameter is precisely the same.

It would help if you kept in mind placing a default value parameter after the parameter without the default value. This is helpful, excluding the use of parameter with default value while calling the function.

For example,

func demoFunction(x : Int, y : Int = 5) {
  print("Parameter without Default Value = \(x)")
  print("Parameter with Default Value = \(y)")

demoFunction(x: 3)
demoFunction(x: 3, y: 8) 
//like variables you can change the default value of a parameter to a new one

What's next?

Congratulations! You deserve to celebrate this moment. You have completed understanding, implementing, and learning one of the crucial topics of programming and, of course, Swift. We encourage you to read Arrays next; till then, have a great time ahead.

Signup now to get notified about our
FREE iOS Workshops!