ios - Swift:字典键包含值仍然是错误零

标签 ios swift xcode dictionary null

当我尝试打印字典键 fromdate 的值时,它显示错误,即使它包含具有该特定键的值。

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

这是在字典中保存值的代码。

 func saveRecentSearch()  {
        var dictSearch = [String:Any]()

        if let onJourney = Global.onWordJ {
            dictSearch["From"] = onJourney.source?.CM_CityName
            dictSearch["Fromid"] = onJourney.source?.CM_CityID
            dictSearch["To"] = onJourney.destination?.CM_CityName
            dictSearch["Toid"] = onJourney.destination?.CM_CityID
            let date = onJourney.journeyDate
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd"
            let myString = formatter.string(from: date!)
            let yourDate: Date? = formatter.date(from: myString)
            formatter.dateFormat = "dd-MMM-yyyy"
            let updatedString = formatter.string(from: yourDate!)
            print(updatedString)
            dictSearch["fromdate"] = updatedString
        }

fromdate 已经保存了那个日期。查看图片

enter image description here

但是当我尝试检索该数据时,在“fromdate”键中发现它为 nil。这是代码。

var arrSearch = [[String:Any]]()

override func viewDidLoad() {
        super.viewDidLoad()
        if let arr = UserDefault["Search"] {
            arrSearch.append(contentsOf: (arr as! [[String:Any]]))
        } 
             self.tblSearch.reloadData()
    }

tableView Method

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "RecentCell") as! RecentCell
        cell.selectionStyle = .none
        let dict = arrSearch[indexPath.row]
        cell.lblFrom.text = (dict["From"] as! String)
        cell.lblTo.text = (dict["To"] as! String)
        let strDate = (dict["fromdate"])
        cell.lblDate.text = (strDate as! String) //This line showing Error
        return cell
    }

代码有什么问题?我得到了 fromdate 键值的所有值。

最佳答案

这是因为 dictSearch 需要 Any 作为变量,但你传递的是 String 因此,它崩溃了:

也许如果所有变量都是字符串,将其更改为:

var dictSearch = [String:String]()

如果不是,则需要将日期转换为任何非字符串

不推荐这样做,但试试这个:

guard let strDate = dict["fromdate"] as? String else { 
    print("error")
    return
} 
yourlabel.text = strDate

关于ios - Swift:字典键包含值仍然是错误零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53737762/

相关文章:

ios - 如何在 Mac OS X 上一步构建 + 运行 cordova 应用程序?

ios - SKLabelNode 不尊重 zPosition?

iphone - 如何通过Uitableview的各个部分获取下一个类?

ios - 如何使用 Instagram API 获取我的关注者的关注者列表

ios - 更改 .swift 以连接到 TableView Controller 而不是 View Controller

swift - MacOs SwiftUI 文本字段焦点效果颜色变化

swift - didUpdateLocation 什么时候被调用?

iOS 魔法记录不保存

objective-c - Objective C arc——保留对类的引用

ios - Firebase Auth 不起作用,但适用于 friend ,很快