1. Home
  2. Training Library
  3. Programming
  4. Programming Courses
  5. Using Advanced Techniques in Swift

Mutating Function


Advanced Swift
Struct Overview
7m 23s
Guard Let
5m 52s

The course is part of this learning path

Start course

This course focuses on advanced techniques in Swift. You'll be introduced to structs and how we can use them in our code.


Hi, within this lecture we're going to see something called mutating function. And it's again related to immutability of the structs. So, can I have a function inside of our class? Of course, we can. Let's create a happyBirthday() function. And in this function I'm going to add to our current age. So, self.age will be += 1, okay? So, that's easy. Can I do that in musician struct? We will see. Let's try that first with our existing class. So, let me comment this out. So, let me comment all of the prints out so that we will have an empty log, okay? So, let's comment out. Let's comment out this as well. So, over here I'm going to call this function versus Mutating Function, okay? Under here I'm going to call my James class. Okay, so class James, sorry, classJames.age. If I print this, let's actually run this because I don't even remember what was our current age. Yeah, it was 52. Now let's call classJames.happyBirthday. And let's then print out one more time to see the new age of James. It will be 53, right? This is what we expect and it will be 53, yes, this is good. And this works as we expect. But can we do that with struct? Yeah, of course, we can have functions inside of our struct, but let's create the same function over here. And let's try to change the self.age and add 1, this will give us an error. Even though age is a variable, this half isn't mutable. Okay, the struct itself is immutable, so we cannot change this. In order to change this, there is a keyword that we can use in front of our function. We can make this function mutating function, okay? And when we do that you will see the error will go away so that we can use the same function as we want inside of our main.swift. So, let's try to do that with our structJames. Okay, let's print out this structJames age, let me comment this out and this one as well. Let me run this and let's see if we get the 51, yep, we have the 51. Let's call structJames.happyBirthday. And let's print the structJames age one more time. So, let's see if we get 52. Here we go. Now, we have the 52. So, you have to keep in mind that if you want to change a variable inside of your struct, you have to make that function mutating function because the self is immutable in structs. So, we're going to stop here and within the next lecture, we're going to see a new concept called tuple.


About the Author
Learning Paths

Atil is an instructor at Bogazici University, where he graduated back in 2010. He is also co-founder of Academy Club, which provides training, and Pera Games, which operates in the mobile gaming industry.

Covered Topics