簡體   English   中英

Alamofire字符串與AnyObject錯誤不同

[英]Alamofire String is not identical to AnyObject error

我在Swift 2中使用Alamofire。因此,我有一些參數:

let parameters = [
        "fullname": fullName.text,
        "username": username.text,
        "email": email.text,
        "password": password.text,
        "country": country
    ]

並通過以下方式發送請求:

Alamofire.request(Method.POST, "http://myapi.mysite.com/users", parameters: parameters)
            .response { request, response, data, error in

但它返回了下一個錯誤,即parameters

'String?' is not identical to 'AnyObject'

我該如何解決?

相信您需要解壓縮文本字段! 自從轉換為Swift 2以來,很多事情發生在我身上。值得一試。

let parameters = [
        "fullname": fullName.text!,
        "username": username.text!,
        "email": email.text!,
        "password": password.text!,
        "country": country
    ]

您在字典中的值是可選類型。 如果用砰的一聲將其解開,那么您應該能夠消除該錯誤!

如果我們仔細觀察一下Alamofire,我們會發現方法請求看起來像這樣:

public func request(
    method: Method,
    _ URLString: URLStringConvertible,
    parameters: [String: AnyObject]? = nil,
    encoding: ParameterEncoding = .URL,
    headers: [String: String]? = nil)
    -> Request

因此,我們可以看到parameters的類型為[String : AnyObject]? ,它本身是可選的,但只能是整個數組。 里面的參數不能是可選的。 您要添加到字典中的參數是可選的,因此有必要將其解包。 在Swift中使用安全結構是相當普遍的,所以強制使用! 僅僅超越編譯器並不是最明智的選擇。 使用if-let來處理它:

if let fullname = fn.text, un = username.text, em = email.text, pwd = password.text {
    let parameters = [
        //...
    ]
} else {
    // handle the situation - inform the user they forgot some fields
}

至於您Cannot call value of non-function type 'NSHTTPURLResponse?' 問題:

問題出在Alamofire 2.0遷移中,響應序列化已迅速改變,因此對於您的情況,請按以下方式使用它:

Alamofire.request(.POST, "https://myapi.mysite.com/users", parameters: parameters) 
    .responseJSON { _, _, result in 
        print(result) 
        // mumbo jumbo
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM