当我尝试打印字典键 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
已经保存了那个日期。查看图片
但是当我尝试检索该数据时,在“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/