ios - 无法将类型 "Any"的值分配给类型 "String?"Swift 3 (iOS)

标签 ios swift

我想从服务器获取 token ,然后将其分配给 token 变量,这样我就可以将其作为 header 传递到我的 .post 请求方法中。

var token = ["X-Auth-Token": ""]

分配过程

token["X-Auth-Token"] = response.result.value!

这样做之后我得到了错误

can not assign value of type "Any" to type "String?"

我该如何绕过或解决这个问题?

全类:

import Alamofire
import UIKit

class InitialViewController: UIViewController {
    let url = "https://api.sis.kemoke.net/auth/login"
    var parameters = ["email": "", "password": ""]
    var token = ["X-Auth-Token": ""]

    // Parameters textfields
    @IBOutlet weak var email: UITextField?
    @IBOutlet weak var password: UITextField?

    // A method for the login button
    @IBAction func loginButton(_ sender: UIButton) {
        parameters["email"] = email?.text
        parameters["password"] = password?.text
        Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: nil).responseJSON {
            (response) in
            print(response.result.value!)
            token["X-Auth-Token"] = response.result.value!
        }
    }
}

最佳答案

我会建议这种方法:

Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: nil).responseJSON {
    (response) in
    if let tokenString = response.result.value as? String {
        token["X-Auth-Token"] = tokenString
    }
}

通过使用 if let tokenString = response.result.value as? String 在尝试将其转换为 String 之前,您将检查 response.result.value 是否为 String。

始终尝试避免像这样显式展开可选的:

token["X-Auth-Token"] = response.result.value as! String

如果 response.result.value 出于某种原因不是字符串,您的应用就会崩溃。 optionals 的主要目的是保护你免受这样的崩溃。

关于ios - 无法将类型 "Any"的值分配给类型 "String?"Swift 3 (iOS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41108421/

相关文章:

ios - pod 更新期间 Cocoapods 错误

ios - 如何以编程方式添加大小类自定义

ios - 如何使用 Objective C 类中的多个参数调用 Swift 函数?

swift - 委托(delegate)(创建 sideMenu 时,委托(delegate)?返回 nil)

ios - 将图像数组保存为 PFFiles

ios - 如何在按钮触及内部时从 Superview 中删除以编程方式创建的 subview ?

iphone - 在不卡住 UI 的情况下执行提取

ios - NSDateFormatter dateFromString崩溃

swift - detached 和 assignCurrentContext 是什么意思?

swift - 我在 Swift UI 结构中可以拥有的状态变量的最大数量是多少,性能会随着变量的增加而降低吗?