How To Share Data Between View Controllers in Swift (iOS)

Recently I've been coding some Swift which is really fun, but being new to mobile development also causes some headaches. One of them was sharing data between view controllers.

I read this article on The Singleton Pattern in Swift which I thought suited this problem perfectly. This way you don't have to pass the data around to every view controller.

You start with creating the singleton class which basically represents an object.

User.swift

class User {
    class var sharedInstance: User {
        struct Static {
            static var instance: User?
            static var token: dispatch_once_t = 0
        }

        dispatch_once(&Static.token) {
            Static.instance = User()
        }

        return Static.instance!
    }

    var userId: Int
    var name: String
}

Now in your view controllers you create a new shared instance of this class. That way you can access the properties when and where you want.

MyViewController.swift

import UIKit

class MyViewController: UIViewController {

    let user = User.sharedInstance

    override func viewDidLoad() {
        super.viewDidLoad()

        self.user.userId = 42
        self.user.name = "Anthoni Giskegjerde"


        println(self.user.userId) // 42

    }
}

That's it! It works really great and is the cleanest way I've found so far. Please leave any comment and I'll try to answer to my best knowledge. Also feel free to suggest better alternatives.


comments powered by Disqus