1

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?

fja
  • 1,823
  • 1
  • 15
  • 28
  • I'd suggest implementing a standard singleton (https://stackoverflow.com/questions/26742138/singleton-in-swift/26743597#26743597), making your properties normal instance properties of the singleton. – Rob Jun 05 '17 at 01:40
  • So basically what is happening is, you just define a class "regularly" without any `class` methods or `static` properties and just create a static instance of the said class? @Rob – fja Jun 05 '17 at 01:53
  • Yep. Like [`URLSession.shared`](https://developer.apple.com/reference/foundation/urlsession/1409000-shared) or [`FileManager.default`](https://developer.apple.com/reference/foundation/filemanager/1409234-default).. – Rob Jun 05 '17 at 02:11
  • Thanks @Rob you've helped me a lot on here :) – fja Jun 05 '17 at 02:13
  • 1
    +1 on the design decision of making properties **instance**, for clarity and consistency. If everything is going to be `class`/`static`, just use the class object and skip the whole `init()` thing... One or the other. – Nicolas Miari Jun 05 '17 at 02:20

1 Answers1

1

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
        }
    }
}
Jack Lawrence
  • 10,664
  • 1
  • 47
  • 61
  • 1
    _"this is not the same as a computed property, where the value is re-created every time"_ - indeed; it is more like a **lazy** property. – Nicolas Miari Jun 05 '17 at 02:18
  • 2
    Thank you Jack for you answer. If you could also incorporate Rob's comment in your post so that future readers could have access to a more complete answer I would really appreciate it. – fja Jun 05 '17 at 02:25