gpt4 book ai didi

ios - 如何在 Swift 4 中将 Any 转换为 Date?

转载 作者:可可西里 更新时间:2023-11-01 01:09:23 27 4
gpt4 key购买 nike

我从服务器收到一个日期:

// It comes from server as Any let.
let userInfo: [AnyHashable : Any]

let userInfoDic = userInfo as NSDictionary
userInfoDic.value(forKey: "gcm.notification.date") as Any

// prints Optional(2018-04-26)

如果我尝试转换为日期,则会抛出错误:

‘Any?’ is not convertible to 'Date'; did you mean to use 'as!' to force downcast?

当我强制执行时,返回一个 fatal error

最佳答案

试试这个:

if let dateString = userInfoDic.value(forKey: "gcm.notification.date") as? String {
let dateFormatter = DateFormatter()
dateFormatter.format = "yyyy-MM-dd"
if let date = dateFormatter.date(from: dateString) {
print(date)
}
}

关于ios - 如何在 Swift 4 中将 Any 转换为 Date?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48684455/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com