Mutability in Swift

Make a change, for once in your life

Image for post
Image for post
Photo by Chris Lawton on Unsplash

Prerequisites:

Terminology

What does Mutability mean?

Value types

struct MyStruct {
var myVal = 5
}
let number: Int = 5
let str: String = "Hello, World!"
let myStructInstance = MyStruct()
let mySecondStructInstance = MyStruct()
myStructInstance = MySecondStructInstance
myStructInstance.myVal = 5
Image for post
Image for post
Image for post
Image for post

Mutating keyword on a struct

The properties of value types cannot be modified within its instance methods by default.

Image for post
Image for post
struct MyStruct {
var myVal = 5
mutating func changeVal(val: Int) {
self.myVal = val
}
}
Image for post
Image for post

Reference types

class MyClass {
var myVal = 5
}
let myClassOne = MyClass()
myClassOne.myVal = 6
class MyClass {
var myVal = 5
func changeVak(val: Int) {
self.myVal = val
}
}
let myClassOne = MyClass()
let myClassTwo = MyClass()
myClassOne = myClassTwo // creates an error
Image for post
Image for post

Conclusion

The Twitter contact:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store