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?
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
})
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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With