Upgrade to PRO for Only $50/Year—Limited-Time Offer! 🔥

Struct vs Class in Swift

Avatar for Laurentiu Laurentiu
February 16, 2017

Struct vs Class in Swift

This topic it is a comparison between structs and classes in Swift, it also presents why you should adopt structs, because coming from Objective-C you are tended to use classes all over the code without having any benefit of Swift features.

Avatar for Laurentiu

Laurentiu

February 16, 2017
Tweet

Other Decks in Programming

Transcript

  1. let car = Vehicle(model: “X”, price: 200, type: .car(licensePlate: “CJ”))

    let bicycle = Vehicle(model: “A”, price: 10, type: .bicycle(chainRings: 100))
  2. struct Car { let brand: String let model: String let

    price: Double init(brand: String, model: String, price: Double) { self.brand = brand self.model = model self.price = price } } let myCar = Car(brand: “Tesla”, model: “S”, price: 100)
  3. struct Car { let brand: String let model: String let

    price: Double } let myCar = Car(brand: “Tesla”, model: “S”, price: 100)
  4. 37 000 000x Faster Swift 2 - Whole Module Optimization

    github.com/knguyen2708/StructVsClassPerformance
  5. 14 000 000x Faster Swift 3 - Whole Module Optimization

    github.com/knguyen2708/StructVsClassPerformance
  6. let a = [1, 2, 3] var b = a

    // not copied b.append(4) // now it’s copied
  7. When I should use a struct ? • The data

    will be used in code across multiple threads
  8. When I should use a struct ? • The data

    will be used in code across multiple threads • Copies should have independent state
  9. When I should use a struct ? • The data

    will be used in code across multiple threads • Copies should have independent state • Encapsulates a few relatively simply data values
  10. When I should use a class ? • You want

    to create shared, mutable state
  11. When I should use a class ? • You want

    to create shared, mutable state • You want to create complex frameworks like Cocoa or Cocoa Touch