您说该object
变量是字典类型。我可能是错的,但我相信您的字典对象语法不正确。字典应采用以下格式:[key 1: value 1, key 2: value 2, key 3: value 3]
.
这是我在操场上成功运行的代码:
//: Playground
import Foundation
let object = Optional([
"currenttime" : "2016-10-14T11:30:12+00:00",
"endtime" : "2016-10-14T14:30:12+00:00",
"success" : 1
])
let obvj = object as AnyObject?
print(obvj) // prints the dictionary object
let ct = obvj!.object(forKey: "currenttime") as! String
print(ct) // prints: 2016-10-14T11:30:12+00:00
// https://developer.apple.com/reference/foundation/dateformatter
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let date = dateFormatter.date(from: ct)
print(date?.description) // prints: Optional("2016-10-14 11:30:12+0000")
object
var 被初始化为可选的字典类型。
你在这里的行:let obvj = object as AnyObject
应该是let obvj = object as AnyObject?
. object
应该转换为可选的 AnyObject,因为它以可选的字典类型开始。
我不确定你string as Date
的工作情况如何。它对我不起作用。也许您在代码中添加了对 Date 的扩展?在上面的代码中,我使用了标准库中的 DateFormatter 并稍微修改了日期字符串以适应预期的格式。我遵循了此处找到的开发人员参考“使用固定格式日期表示”中的示例:
https://developer.apple.com/reference/foundation/dateformatter