Skip to content

Instantly share code, notes, and snippets.

@ncooke3
Last active July 28, 2019 04:59
Show Gist options
  • Save ncooke3/295f7769fd852f74bf419030b74c6eba to your computer and use it in GitHub Desktop.
Save ncooke3/295f7769fd852f74bf419030b74c6eba to your computer and use it in GitHub Desktop.
Example of key difference between Classes and Structs in Swift
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