Last active
July 28, 2019 04:59
-
-
Save ncooke3/295f7769fd852f74bf419030b74c6eba to your computer and use it in GitHub Desktop.
Example of key difference between Classes and Structs in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
// Key Idea: Classes are Reference types and Structs are Value types! | |
class Runner { | |
var type: String | |
var level: Int | |
var pro: Bool | |
init(type: String, level: Int, pro: Bool) { | |
self.type = type | |
self.level = level | |
self.pro = pro | |
} | |
} | |
// Classes are reference types. After we set copycat = sprinter, | |
// copycat and sprinter now point to the same instance of the Runner | |
let sprinter = Runner(type: "sprinter", level: 1, pro: false) | |
let copycat = sprinter | |
// Since copycat references the same instance of the Runner object as | |
// sprinter does, we are changing the object that copycat and sprinter | |
// point to | |
copycat.type = "distance" | |
print(sprinter.type) // prints 'distance' because the instance that sprinter | |
// has been modified | |
struct Jogger { | |
var age: Int | |
var fast: Bool | |
// itializer not required in structs! | |
} | |
let hobbyJogger = Jogger(age: 21, fast: true) | |
var copyHobbyJogger = hobbyJogger | |
copyHobbyJogger.fast = false | |
print(hobbyJogger.fast) // prints true because copyHobbyJogger and hobbyJogger don't | |
// refer to the same instance of Runner but rather the value | |
// of the Runner object itself! | |
// Classes offer inheritance. Structs don't have inheritance so they are light weight |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment