我从服务器收到一个日期:
// 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/