将Obj-C转换为Swift

时间:2015-06-09 17:19:50

标签: objective-c swift layer

我无法将此行转换为Swift:

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

这是我在Swift中的界限:

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

任何人都对我做得不正确的事情有所了解吗?

2 个答案:

答案 0 :(得分:1)

我会使用"完成处理程序"来翻译Swift中的这种函数:

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

并称之为:

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

修改

根据您的评论,这是一个类功能中的新示例,以及" 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 :(得分:1)

如果您想调用该方法,它将在Objective-C中显示(我认为您正在使用this

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

在Swift中

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


})