Swift 3报错:无法将类型'Date?'赋值给类型'String?'
解决:无法将类型'Date?'赋值给类型'String?'
嘿,这个问题其实挺典型的——你现在犯了一个方向搞反的小错误:dateFormatter.date(from:)返回的是Date?类型,但UILabel的text属性需要的是String?类型,直接赋值当然会类型不匹配啦!
问题根源
你现在的代码是把字符串转成了Date,但Label需要的是字符串展示,所以得把Date再转回字符串,用DateFormatter的另一个方法string(from:)来完成这个操作。另外还要注意:
- 不要用
!强制解包date,万一match.dateTimeGMT是无效的日期字符串,你的APP会直接崩溃 DateFormatter同时设置dateFormat和dateStyle是冲突的——自定义格式dateFormat的优先级更高,dateStyle会被忽略,你得根据需求二选一
修正后的完整代码
let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") // 如果你需要自定义格式,保留这个,注释掉dateStyle dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" // 如果想用系统预设的中等样式,就打开这个,注释掉dateFormat // dateFormatter.dateStyle = .medium // 安全解包,处理可选值,避免崩溃 if let dateString = match.dateTimeGMT, let date = dateFormatter.date(from: dateString) { print("date: \(date)") // 把Date转成符合格式的字符串,再赋值给Label cell.dateTimeGMTLabel.text = dateFormatter.string(from: date) } else { // 处理日期解析失败的情况,给个默认提示 cell.dateTimeGMTLabel.text = "Invalid Date" }
关键知识点
- DateFormatter的互逆操作:
date(from: String):将字符串解析为Datestring(from: Date):将Date格式化为字符串
- 可选值安全处理:用
if let进行可选绑定,比强制解包!更安全,能避免无效输入导致的崩溃 - 格式优先级:当同时设置
dateFormat和dateStyle/timeStyle时,自定义格式dateFormat会覆盖样式设置,二者选其一即可
内容的提问来源于stack exchange,提问作者Nishantkumar Rai
相关产品推荐
相关产品推荐

