Converting Obj-C to Swift

I am having trouble converting this string 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 }

      

Does anyone have any idea what I'm not doing right?

+3


source to share


2 answers


I would translate this function into 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 inside a class function and with "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
})

      

+1


source


If you want to make a call to this method it would look like Objective-C (I think you are 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


})

      

+1


source







All Articles