fja
fja

Reputation: 1839

How to initiate a singleton in Swift?

I have a class called HTTPHelper which is responsible for doing all my back end API requests. All methods in this class are class methods. As you know instance properties cannot be used from within a class method. I have some properties that need initialization with a do{}catch{} block which currently are being initiated from within an init(){} like so:

class HTTPHelper{
    init(){
        do {
            //initiate property
        } catch{}
    }
}

My question is, is there a mechanism similar to an init(){} that would initiated a static property for a singleton?

Upvotes: 1

Views: 178

Answers (1)

Jack Lawrence
Jack Lawrence

Reputation: 10772

You can assign a property to the result of a closure or function (note the = and () at the end to execute the closure—this is not the same as a computed property, where the value is re-created every time). Instead, the first time you access the property the value is lazily computed once using your function/closure and then stored in the property for future access.

class MyClass {
    static let myProperty: String = {
        do {
            return try blah()
        } catch {
            // error handling
        }
    }()
}

Of course, this is just a special case of assigning the result of a function to a property:

class MyClass {
    static let myProperty: String = MyClass.createMyString()

    static func createMyString() -> String {
        do {
            return try blah()
        } catch {
            // error handling
        }
    }
}

Upvotes: 1

Related Questions