2014-10-01 44 views
7

如何在swift中編寫此塊函數?我已經讀過這個主題,但是這個語法對我來說並不合理。在Swift中寫入塊函數

MyAppRequest *request = [_agent login]; 
    [request sendWithLoadMessage:@"Signing In" 
    successMessage:@"Signed In" 
    failureMessage:@"Failed to log in" 
    recoveryOptions:@"If you keep having trouble, try going to http://mystrou.firehosehelp.com and try loggin in there. If that fails, try resetting your password" 
    success:^(MyAppResponse *response) { 
     PREFS.authToken = _agent.accessToken; 
     [_delegate loginViewController:self loggedInAgent:_agent]; 
    } failure:^(MyAppResponse *response) { 

    }]; 
+1

請張貼更多的代碼 - 有呼叫丟失的部分。 – fluidsonic 2014-10-01 04:39:28

+0

確定我已經相應更新 – YichenBman 2014-10-01 04:42:41

回答

19

實際上並不難。在Swift中稱爲關閉)。

public func someFunction(success: (response: AnyObject!) -> Void, failure: (error: NSError?) -> Void) { 

} 

這就是你怎麼稱呼它。

someFunction(success: { (response) -> Void in 
    // Handle success response 
}) { (error?) -> Void in 
    // Do error handling stuff 
} 

在你的情況,我得到這個塊處理一些服務器響應。最有可能登錄。如果網絡操作成功,將調用success塊。在裏面,你保存從你的服務器收到的訪問令牌。如果網絡請求失敗,則調用failure塊。您可能希望將錯誤記錄下來,向用戶顯示一條警告信息。

如果您對我建議參考這兩個網站的語法感到困惑。對於Objective-C block syntaxSwift closure syntax

0

感謝@isuru我想通了這一點:

let request: MyAppRequest = agent .login() 

request .sendWithLoadMessage("Signing in", 
     successMessage: "Signed in", 
     failureMessage: "Failed to login", 
     recoveryOptions: "Figuring it out", 
     success: { (response: MyAppResponse!) -> Void in MyAppSettings().authenticatingToken = agent.accessToken 
     }) { (response: MyAppResponse!) -> Void in 
      var alert = UIAlertController(title: "Oops!", message: "You haven't figured out the token thing!", preferredStyle: UIAlertControllerStyle.Alert) 

      alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil)) 
      self.presentViewController(alert, animated: true, completion: nil) 
    }