委托方法中带有completionHandler ...的块的Swift语法

Sta*_*tan 8 closures block objective-c ios swift

这是常规NSURLSession完成块问题的一个问题,我很快就解决了Swift语法问题.该方法是身份验证委托回调,在auth challenge上调用; 开发人员使用NSURLCredential NSError调用完成块.

Objective-C方法如下所示:

-(void) provideUsernamePasswordForAuthChallenge:(NSURLAuthenticationChallenge *)authChallenge completionHandler:(void (^)(NSURLCredential *, NSError *))completionHandler{

    NSURLCredential* credential = [NSURLCredential credentialWithUser:@"myname" 
                                                             password:@"mypass" 
                                                          persistence:NSURLCredentialPersistenceForSession];
    completionHandler(credential, nil);
}
Run Code Online (Sandbox Code Playgroud)

我认为我在Swift中最接近的是:

func provideUsernamePasswordForAuthChallenge(authChallenge: NSURLAuthenticationChallenge!,  completionHandler:(() -> (NSURLCredential?, NSError?)) {

    var cred = NSURLCredential(user: "myname", password: "mypass", persistence: NSURLCredentialPersistence.ForSession)
    return (cred, nil)
})
Run Code Online (Sandbox Code Playgroud)

但是,它仍然在bar.有什么建议?

Lou*_*nco 15

  1. void函数是(Type1,Type2) - >()
  2. 你需要为方法本身添加 - >()
  3. 你需要用(cred,nil)调用completionHandler,而不是返回一个元组

    func provideUsernamePasswordForAuthChallenge(authChallenge: NSURLAuthenticationChallenge!,  completionHandler:(NSURLCredential?, NSError?)->()) ->() {
    
       var cred = 
          NSURLCredential(user: "myname", password: "mypass", 
             persistence: NSURLCredentialPersistence.ForSession)
       completionHandler(cred, nil)
    }
    
    Run Code Online (Sandbox Code Playgroud)