Quantcast
Channel: User Steven Fisher - Stack Overflow
Viewing all articles
Browse latest Browse all 40

Swift lazy static member initialization

$
0
0

Starting from this code:

class Formatters {    static let shared = Formatters()    var humaneNumbers: NumberFormatter;    private init() {        humaneNumbers = NumberFormatter()        humaneNumbers.numberStyle = .decimal    }}

(Thread safety not included here.)

I need to call this as Formatters.shared.humaneNumbers; I'd much rather just call Formatters.humaneNumbers.

Is there a way to do this with only a static property? I tried this:

class Formatters {    static var humaneNumbers: NumberFormatter {        let humaneNumbers = NumberFormatter()        humaneNumbers.numberStyle = .decimal        return humaneNumbers    }}

…but that becomes a static calculated property, so it's called every time instead of just once.

Then, of course, there's this approach:

class Formatters {    static let humaneNumbers = NumberFormatter()}

But that gives me an uncustomized NumberFormatter.

Am i missing something?


Viewing all articles
Browse latest Browse all 40

Latest Images

Trending Articles





Latest Images