Converting Obj-C to Swift

228 views Asked by At

I'm having trouble converting this line to Swift:

(void)authenticateLayerWithUserID:(NSString *)userID completion:(void (^)(BOOL success, NSError * error))completion { }

Here's my line in Swift:

func authenticateLayerWithUserID(userID: NSString) {(success: Bool, error: NSError?) -> Void in }

Anyone have some insight into what I'm not doing correctly?

2

There are 2 answers

4
Eric Aya On BEST ANSWER

I would translate this kind of function in Swift with a "completion handler":

func authenticateLayerWithUserID(userID: NSString, completion: (success: Bool, error: NSError?) -> ()) {
    if userID == "Jack" {
        completion(success: true, error: nil)
    }
}

And call it like this:

authenticateLayerWithUserID("Jack", { (success, error) in
    println(success) // true
})

EDIT:

Following your comments, here's a new example within a class function, and with an "if else":

class MyClass {
    class func authenticateLayerWithUserID(userID: NSString, completion: (success: Bool, error: NSError?) -> ()) {
        if userID == "Jack" {
            completion(success: true, error: nil)
        } else {
            completion(success: false, error: nil)
        }
    }
}

MyClass.authenticateLayerWithUserID("Jack", completion: { (success, error) in
    println(success) // true
})

MyClass.authenticateLayerWithUserID("John", completion: { (success, error) in
    println(success) // false
})
0
Diego Freniche On

If you want to make a call to that method, it will look like this in Objective-C (I think you're using this:

[self authenticateLayerWithUserID:userIDString completion:^(BOOL success, NSError *error) {
            if (!success) {
                NSLog(@"Failed Authenticating Layer Client with error:%@", error);
            }
 }];

In Swift

var c: MyClass = MyClass()
    c.authenticateLayerWithUserID("user", completion: { (boolean, error) -> Void in


})