Skip to content

Instantly share code, notes, and snippets.

@codephillip
Created September 22, 2017 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codephillip/6936015225efc885016c605f7a7245f3 to your computer and use it in GitHub Desktop.
Save codephillip/6936015225efc885016c605f7a7245f3 to your computer and use it in GitHub Desktop.
Class vs Structure difference in swift. Structures provide better threading functionality
import UIKit
/*
CREDIT: http://agostini.tech/2017/09/03/structures-vs-classes-in-swift/
*/
// MARK: - Structures Example
struct Book {
var title: String
var author: String
}
let originalBook = Book(title: "How to survive on less than 2000€ in Dublin", author: "Anonymous")
var copiedBook = originalBook
copiedBook.author = "Some guy"
print(originalBook)
// MARK: - Classes Example
class Planet: CustomDebugStringConvertible {
var name: String
var galaxy: String
init(name: String, galaxy: String) {
self.name = name
self.galaxy = galaxy
}
var debugDescription: String {
return "\(name):\(galaxy)"
}
}
let earth = Planet(name: "earth", galaxy: "current one")
let backupEarth = earth
backupEarth.name = "backup earth"
print(earth)
// MARK: - Arrays Example
var planets = [Planet(name: "abc123", galaxy: "andromeda"), Planet(name: "xyz987", galaxy: "milkyway")]
var newPlanets = planets
newPlanets.append(Planet(name: "earth", galaxy: "this one"))
print("Original: ", planets)
print("Copy: ", newPlanets)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment