2016-09-22 43 views
1

我正在轉換爲Swift 3.0,並有Alamofire定製Router類。我的代碼如下:Alamofire 4.0路由器類型的表達式是不明確的,沒有更多的上下文

enum Router: URLRequestConvertible { 

    case get(query: String, params: [String: AnyObject]?) 
    case post(query: String, params: [String: AnyObject]?) 
    case put(query: String, params: [String: AnyObject]?) 
    case delete(query: String, params: [String: AnyObject]?) 

    var urlRequest: NSMutableURLRequest { 

     // Default to GET 
     var httpMethod: HTTPMethod = .get 

     let (path, parameters): (String, [String: AnyObject]?) = { 
      switch self { 
      case .get(let query, let params): 
       // Set the request call 
       httpMethod = .get 
       // Return the query 
       return (query, params) 
      case .post(let query, let params): 
       // Set the request call 
       httpMethod = .post 
       // Return the query 
       return (query, params) 
      case .put(let query, let params): 
       // Set the request call 
       httpMethod = .put 
       // Return the query 
       return (query, params) 
      case .delete(let query, let params): 
       // Set the request call 
       httpMethod = .delete 
       // Return the query 
       return (query, params) 
      } 
     }() 


     // Create the URL Request 
     let urlRequest: NSMutableURLRequest 
     if let url = URL(string: Globals.BASE_URL + path) { 
      urlRequest = NSMutableURLRequest(url: url) 
     } else { 
      urlRequest = NSMutableURLRequest() 
     } 

     // set header fields 
     if let key = UserDefaults.standard.string(forKey: Globals.NS_KEY_SESSION) { 
      urlRequest.setValue(key, forHTTPHeaderField: "X-XX-API") 
     } 

     // Add user agent 
     if let userAgent = UserDefaults.standard.string(forKey: Globals.NS_KEY_USER_AGENT) { 
      urlRequest.setValue(userAgent, forHTTPHeaderField: "User-Agent") 
     } 

     // Set the HTTP method 
     urlRequest.httpMethod = httpMethod.rawValue 

     // Set timeout interval to 20 seconds 
     urlRequest.timeoutInterval = 20 

     return Alamofire.URLEncoding().encode(urlRequest as! URLRequestConvertible, with: parameters) 
    } 

    func asURLRequest() throws -> URLRequest { 
    } 
} 

這是給我的錯誤在Alamofire.URLEncoding()說明Type of expression is ambiguious without more context。這是什麼意思?

Alamofire文檔在https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md#parameter-encoding-protocol,他們有代碼

public protocol ParameterEncoding { 
    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest 
} 

回答

0

這是近的How to migrate Alamofire router class to Swift 3? 重複檢查出來,你會看到如何使用新ParameterEncoding和特別是URLRequestConvertible現在實施了func asURLRequest() throws -> URLRequest而不是var了。

+0

感謝執行'func'而不是'var'確實有所幫助。 –

相關問題