Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Obj-C to Swift

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 Answers

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
})
like image 65
Eric Aya Avatar answered May 18 '26 10:05

Eric Aya


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


})
like image 40
Diego Freniche Avatar answered May 18 '26 09:05

Diego Freniche



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!