0

I'm trying to convert this to swift:

+ (instancetype)sharedGameKitHelper
{
    static GameKitHelper *sharedGameKitHelper;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedGameKitHelper = [[GameKitHelper alloc] init];
    });
    return sharedGameKitHelper;
}

now I dont have any experience with Objective-C so I used this converter: Objectivec2swift.com and it gave me this:

class func sharedGameKitHelper() -> Self {
    var sharedGameKitHelper: GameKitHelper?
    var onceToken: dispatch_once_t
    dispatch_once(onceToken, {() -> Void in
        sharedGameKitHelper = GameKitHelper()
    })
    return sharedGameKitHelper!
}

It gives me some error, and I have no clue what to do with it, so I would appreciate a bit of help here.

Errors:

Errors

Benja0906
  • 1,437
  • 2
  • 15
  • 25
  • In the sense that he *should* be using that method, yes, but there's a specific syntax question about how to use and old C API with Swift that's useful in itself. – BaseZen Sep 08 '16 at 16:11

1 Answers1

0

For compatibility with old C API, need to use rare & operator to deal with the address-of nature of the parameter. The onceToken needs a unique value. Also you need the explicit type not Self. Finally for compactness you can use trailing closure syntax and inferred function signature.

class GameKitHelper {
    static var onceToken: dispatch_once_t = 1
    class func sharedGameKitHelper() -> GameKitHelper {
        var sharedGameKitHelper: GameKitHelper?
        dispatch_once(&onceToken) { sharedGameKitHelper = GameKitHelper() }
        return sharedGameKitHelper!
    }
}

However, that methodology is non-idiomatic & overcomplicated. See:

http://krakendev.io/blog/the-right-way-to-write-a-singleton

And in there references back to SO:

Using a dispatch_once singleton model in Swift

Community
  • 1
  • 1
BaseZen
  • 8,650
  • 3
  • 35
  • 47
  • It gives me an error at `dispatch_once(&oncetok...` it says: "Thread 1: EXC_BAD_ACCESS (code=1, address=0x11)" – Benja0906 Sep 08 '16 at 16:25
  • The dispatch_once_t variable cannot be a local variable of the function, it has to be a *static* variable (as it is in the Objectice-C code), compare http://stackoverflow.com/a/19845164/1187415. The correct use of dispatch_once in Swift is also demonstrated in the accepted answer of the linked-to "duplicate". – Martin R Sep 08 '16 at 16:43
  • Thank you, fixed even though dup just so it's not wrong. Unless you think I should just delete this answer. – BaseZen Sep 08 '16 at 16:52
  • It gives me the same error though – Benja0906 Sep 08 '16 at 17:23
  • The token must be initialized to *zero*. – Martin R Sep 08 '16 at 17:29