Skip to content

Instantly share code, notes, and snippets.

@PetreVane
Created November 29, 2019 10:31
Show Gist options
  • Save PetreVane/d7f0c583a03638908dbd5f16722dcac3 to your computer and use it in GitHub Desktop.
Save PetreVane/d7f0c583a03638908dbd5f16722dcac3 to your computer and use it in GitHub Desktop.
class MusicPlayer {
init() {
print("Music Player has started")
}
}
class Singer {
/*
The static part means this property is shared by the class rather than instances of the class.
Meaning that you use Singer.musicPlayer rather than object.musicPlayer.
*/
static let musicPlayer = MusicPlayer()
init() {
print("Singer has begun singing")
}
}
let singer = Singer()
// Only after calling Singer.musicPlayer, does the MusicPlayer class get initialised
Singer.musicPlayer
/*
Yes: all Swift static let singletons are automatically lazy – they only get created when they are
needed. It’s so easy to do, and yet perfectly efficient too
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment