2016-11-06 163 views
0

即時得到這個錯誤「類聲明不能關閉超值‘viewcontainer’外範圍定義爲」自定義協議

我創建了一個叫做網絡協議NetworkResponse這對sucessResponse和onErrorResponse兩種方法。

然後,我有一個名爲回調類,從NetworkResponse,被迫延伸到執行該方法。

這裏是我的功能:

public func login (callback : Callback, viewController : UIViewController) { 



     let callbackInstance: NetworkResponse = { 

      class callback : Callback { 



       override func onSucessResponse(response : NSDictionary){ 

        viewController.dismiss(animated: true, completion: nil) 

       } 
       override func onErrorResponse(message : String, code : Int){ 
        print("error") 
       } 
      } 

      return callback() 
     }() 

     postPath(callback: callbackInstance as? Callback) 

} 

我想拒絕來自匿名類控制器。

任何recomendation?

+0

你是Java開發人員嗎? – NRitH

+0

是的,我是。 swift中的新人 –

+1

我想你應該用'closure'而不是'protocol'來定義'onSuccess'和'onError'回調。 – Enix

回答

1

無需定義協議和回調類。關閉正是你需要的。

import UIKit 

public class TestInnerClass: UIViewController { 

    public func login(successCallback: ((response: NSDictionary) -> Void), errorCallback: ((message: String, code: Int) -> Void)) { 

     let success = false 
     let response = NSDictionary() 

     // 
     // Make your login request here, and change the `success` value depends on your response 
     // let response = ... 
     // 
     // If you are making a async request to login, then put the following codes inside your request callback closure. 
     // 

     if success { 
      successCallback(response: response) 
     } else { 
      errorCallback(message: "error occurred", code: -1) 
     } 
    } 

    override public func viewDidLoad() { 
     super.viewDidLoad() 

     login({ 
       (response) in 
       // Get Called when success 
       self.dismissViewControllerAnimated(true, completion: nil) 
      }, errorCallback: ({ 
       // Get called when failed 
       (message, code) in 
       print(message) 
      })) 
    } 
} 

我已經寫了一些sample codes您的情況,我的GitHub庫,而這個例子是使用Alamofire進行網絡請求,僅供參考。 PS:由於我仍然使用Xcode 7.3.1,因此您可能需要對上述代碼進行一些更改以採用swift 3語法要求。

+0

最佳答案。不使用協議!使用閉包:) –