0

I think my previous question was too vague. Let me try again.

I'm trying to hold user information by creating a singleton. After a bit of research, this is what I understood.

     Class UserInfo {
             var userFirstName: String? 
             var userLastName: String?
             /*I'll add all other variables here*/

    }


let sharedInfo = UserInfo()

Am I on right path?

user2832411
  • 105
  • 1
  • 11

1 Answers1

1

EDIT: For Swift 1.2 and higher (Thanks Will M)

class UserInfo  {
   static let sharedUserInfo = UserInfo()
   var firstName: String?
   var lastName: String?
}

For Swift earlier than 1.2

Something along the lines of:

class UserInfo
{
    // Singleton Setup

    private static var info: UserInfo?

    class func sharedUserInfo() -> UserInfo
    {
        if self.info == nil
        {
            self.info = UserInfo()
        }

        return self.info!
    }

    // Class properties

    var firstName: String?
    var lastName: String?
}

let user = UserInfo.sharedUserInfo()
user.firstName = "Fred"
user.lastName = "Smith"

I would also recommend making sure that a singleton is really what you want, because depending on how you use it, you could run into some race conditions with threading.

mbottone
  • 1,219
  • 9
  • 13
  • Singletons in newer swift is much easier than that and quite safe. [link](http://stackoverflow.com/questions/24024549/dispatch-once-singleton-model-in-swift) – Will M. Jun 30 '15 at 18:50
  • That is much better. Thanks! – mbottone Jun 30 '15 at 18:59
  • Thanks @mbottone but somehow if I use your first example, it gives me error saying "static properties are only allowed within structs and enums; use 'class' to declare a class property" And when I user 'class' instead of 'static' it gives me error saying "userInfo cannot be constructed becuase it has no accessible initializers" Please help :( – user2832411 Jul 06 '15 at 18:17
  • I just updated my swift to 1.2 and your code is working just fine! Thank you! – user2832411 Jul 11 '15 at 22:48