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

标签 ios swift casting ios11 swift4

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

// 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/

相关文章:

regex - 如何获取包含属于数组的单词的字符串的开头?

ios - 为什么 calculateAccumulatedFrame 会给出意想不到的 CGRect?

go - 验证 int 和 float64 的 reflect.Type 的其他方法

c++ - type(myVar) 和 (type)myVar 的名称是什么?他们都是不好的做法吗?

ios - 如何知道NSOperation操作是否完成?

ios - 如何从 JSON 数组 SwiftyJSON 获取数据?

ios - Swift string more than operator 是如何工作的

c# - 在 Windows 窗体中将 int 转换为 Color

iOS 7 使用 AVPlayer 在锁定屏幕上倒回歌曲

ios - Swift - 在 Collection View 中选择项目