Created
November 29, 2019 10:31
-
-
Save PetreVane/d7f0c583a03638908dbd5f16722dcac3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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