Why does the following code give me the error:
Invalid type in JSON write (_SwiftValue).
The error is thrown on this line:
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 isFunction
it's notTimeInterval
. I needed to changeDate.
toDate().
ie use the instance method rather than the static method. When you're dictionary values areAny
then this sort of issue doesn't get found until a runtime error where it can't serialize the dictionary to a JSON string...
Had the same problem and error as you! FINALLY found the issue...
My code:
params = [
"gender": request.gender.first ?? "",
"age": 15
]
Problem: Even though request.gender.first ?? ""
returns a string, its a type of String.Element
, which ANY JSONEncoder
or JSONSerialization
cannot encode (and is not in the list of types it can handle, according to documentation).
Solution:
params = [
"gender": request.gender.first?.description ?? "",
"age": 15
]
Typically, just make sure its a string or an appropriate number the Encoders can handle...
Just in case anyone is still having problems and is using Enums, another cause may be if you are passing an Enum value and not it's rawValue.
Example:
enum Status: String {
case open
case closed
}
instead of passing the enum:
params = ["status": Status.open]
pass
params = ["status": Status.open.rawValue]
I got this error when used a Set
that is linked with Foundation NSSet
.
let myArray = Array(mySet)