Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // CLASSES
- // Like structs but with 5 important differences:
- // 1) Classes don't come with a memberwise initializer.
- // 2) Classes can inherit from other classes.
- // 3) A copy of a class points to the same thing as the original.
- // Changing one changes the other.
- // 4) They have deinitializers (deinit).
- // 5) Mutability: No need to add "mutating" to methods that change vars.
- // Create your own init
- class Dog {
- var name: String
- var breed: String
- init(name: String, breed: String) {
- self.name = name
- self.breed = breed
- }
- }
- let chico = Dog(name: "Chico", breed: "Boxer Mix")
- // INHERITANCE
- // Also known as subclassing
- // Class you inherit from is the "parent" or "super" class
- // New class is the "child" class
- // super.init is always called from child's init()
- class Poodle: Dog {
- init(name: String) {
- super.init(name: name, breed: "Poodle")
- }
- }
- // Another example of inheritance
- class Handbag {
- var price: Int
- init(price: Int) {
- self.price = price
- }
- }
- class DesignerHandbag: Handbag {
- var brand: String
- init(brand: String, price: Int) {
- self.brand = brand
- super.init(price: price)
- }
- }
- let gucci = DesignerHandbag(brand: "Gucci", price: 5)
- // OVERRIDING METHODS
- class Superhero {
- func superpower() {
- print ("Super strength")
- }
- }
- class Batman: Superhero {
- override func superpower() {
- print("I'm rich")
- }
- }
- let superman = Superhero()
- superman.superpower() // "Super strength"
- let batman = Batman()
- batman.superpower() // "I'm rich"
- // FINAL CLASSES
- // Keyword "final" prevents other classes from inheriting from it
- // and therefore incapable of overriding your methods
- final class Spaceship {
- var name: String
- init(name: String) {
- self.name = name
- }
- func message() {
- print("The name of the ship is \(name)")
- }
- }
- // class Enterprise: Spaceship {} <--- Returns error message
- // COPYING CLASSES
- class Singer {
- var name: String
- init(name: String) {
- self.name = name
- }
- }
- var taylor = Singer(name: "Taylor")
- print(taylor.name) // "Taylor"
- var justin = taylor
- justin.name = "Justin"
- print(justin.name) // "Justin"
- print(taylor.name) // "Justin"
- // DEINITIALIZERS
- class EmptyClass {
- }
- class Soldier {
- var name = "Greg"
- init() {
- print("Hey, my name is \(name) and I'm alive and fighting!")
- }
- func message() {
- print("Just wanted to say hello!")
- }
- deinit {
- print("Now I'm dead... thanks a lot, deinit!")
- }
- }
- for _ in 1...2 {
- let greg = Soldier()
- greg.message()
- }
- // MUTABILITY
- class Artist {
- var name: String
- init(name: String) {
- self.name = name
- }
- }
- let joanne = Artist(name: "Joanne")
- print(joanne.name) // "Joanne"
- joanne.name = "Emma"
- print(joanne.name) // "Emma"
- // Doing the above with a struct would not be possible
Advertisement
Add Comment
Please, Sign In to add comment