JSONSerialization Invalid type in JSON write (_SwiftValue)

前端 未结 10 938
情书的邮戳
情书的邮戳 2020-12-14 14:14

Why does the following code give me the error:

Invalid type in JSON write (_SwiftValue).

The error is thrown on this line:

10条回答
  •  再見小時候
    2020-12-14 14:34

    I was getting this runtime error because my dictionary was like this:

    var dictionary: [AnyHashable: Any] = [:]
    let elapsedTime = Date.timeIntervalSince(oldDate)
    dictionary["elapsedTime"] = elapsedTime
    

    Can you tell me what the problem is? hover your mouse on the box below to see answer!

    elapsedTime's type is Function it's not TimeInterval. I needed to change Date. to Date(). ie use the instance method rather than the static method. When you're dictionary values are Any then this sort of issue doesn't get found until a runtime error where it can't serialize the dictionary to a JSON string...

提交回复
热议问题