Chapter 5. Data Storage

Games are apps, and apps run on data. Whether it’s just resources that your game loads or saved-game files that you need to store, your game will eventually need to work with data stored on the flash chips that make up the storage subsystems present on all iOS devices.

In this chapter, you’ll learn how to convert objects into saveable data, how to work with iCloud, how to load resources without freezing up the rest of the game, and more.

5.1 Storing Structured Information


You want to store and load your game’s information in a way that produces data that’s easy to read and write.


Make the objects that you want to store and load conform to the Codable class, and use one of the Encoder and Decoder classes to convert the objects to raw data that you can save and load.

For example, let’s assume that you want to store a saved game. Saved games contain three things: the level number the player is on, the name of the player, and the set of achievements that they’ve earned in this game. The achievements themselves are represented as an enumeration:

// The list of achievements that the player can get.
enum Achievements : String, Codable {
    case startedPlaying
    case finishedGameInTenMinutes
    case foundAllSecretRooms

// The data that represents a saved game.
class SavedGame : Codable {

    var levelNumber = 0
    var playerName = ""

    var achievements : Set<Achievements> = []

let savedGame = SavedGame()

// Store some data
savedGame.levelNumber = 3
savedGame ...

Get iOS Swift Game Development Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.