我使用Swiftify将一些Obj C代码转换为Swift并得到了我不知道如何处理的错误

use*_*721 -4 objective-c swift

这是已翻译的代码的一部分:

目标C:

[SPTRequest userInformationForUserInSession:session callback:^(NSError *error, SPTUser *user) {
        if (error != nil) {
            UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"Getting User Info Failed"
                                                           message:error.userInfo[NSLocalizedDescriptionKey]
                                                          delegate:nil
                                                 cancelButtonTitle:@"OK"
                                                 otherButtonTitles:nil];
            [view show];
            return;
        }
Run Code Online (Sandbox Code Playgroud)

迅速:

1    SPTRequest.userInformationForUserInSession(session, callback: {(error: NSError, user: SPTUser) -> Void in
2        if error != nil {
3           var view: UIAlertView = UIAlertView(title: "Getting User Info Failed", message: error.userInfo[NSLocalizedDescriptionKey], delegate: nil, cancelButtonTitle: "OK", otherButtonTitles: "")
4            view.show()
5           return
6        }
Run Code Online (Sandbox Code Playgroud)

错误:

1: Cannot convert value of type '(NSError, SPTUser) -> Void' to expected argument type 'SPTRequestCallback!'

2: Value of type 'NSError' can never be nil, comparison isn't allowed

3: Cannot subscript a value of the type '[NSObject: AnyObject]' with an index of type 'String'

我最困惑的是Objective C如何工作,但Swift翻译却没有.我的桥接标题也设置正确.

谢谢!

mat*_*att 5

不要盲目或机械地翻译.想想代码是如何工作的.为了error成为nil,在Swift中,它需要是一个可选的.但在您的代码中,它不是可选的.你需要键入erroras NSError?,而不是as NSError.

我打赌,此外,如果有错误,SPTUser user将是nil.但你也没有允许这样做.你需要输入这个SPTUser?,而不是SPTUser.

(您可能必须在此处使用感叹号而不是问号;这一切都取决于原始API的标记方式.但首先使用问号进行尝试.)

您也可能遇到麻烦,因为API类型userid,即AnyObject.

我认为,最好的入门方法是让Swift类型推理为您工作.这对我来说很好:

    SPTRequest.userInformationForUserInSession(session) { 
        (error, user) -> Void in
        //
    }
Run Code Online (Sandbox Code Playgroud)

通过这种方式,errorNSError!userAnyObject!,自动.当然,现在你需要转向userSPTUser,但是当你来到它时你可以越过那座桥.