从 AnyObject 访问值时发生异常

Exception generated while accessing value from AnyObject

产生这种错误

[_SwiftValue objectForKey:]: unrecognized selector sent to instance 0x600000a805a0

当我运行下面的代码

 let obvj = object as AnyObject
 print(obvj)
 let ct = obvj.object(forKey: "currenttime") as! Date

此处对象的值为

Optional({
    currenttime = "2016-10-14 11:30:12 +0000";
    endtime = "2016-10-14 14:30:12 +0000";
    success = 1;
})

虽然这在 Swift 2.2

中运行良好

错误是说您的 object_SwiftValue 的类型,您无法使用它访问 Objective C 方法,为了解决您的问题,请将您的 object 转换为 [String: Any] 并使用 subscript 而不是 object(forKey:).

if let obvj = object as? [String: Any] {
    if let ct = obvj["currenttime"] as? Date

    }
}

您声明 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 并稍微修改了日期字符串以适合预期的格式。我按照开发人员参考 "Working With Fixed Format Date Representations" 中的示例进行了操作:

https://developer.apple.com/reference/foundation/dateformatter