I have converted to Swift 3 and I have received the following errors when assigning to AnyObject the JSONSerialization.jsonObject. Has anyone come across this issue and know the fix?
Asked
Active
Viewed 650 times
-4
-
3Post actual code, not an image of the code. People often want to reproduce your code to try and troubleshoot it – Takarii Sep 16 '16 at 10:29
2 Answers
0
Since the last Swift 3 update most of the return types changed from AnyObject
to Any
and downcast is not allowed, so in such situation you are forced to use explicit cast. That means you should make a couple of guard
statements or use optional chaining if let
defining each necessary field. Consider using map
, filter
, reduce
if possible to make your code more elegant. Example:
guard
way:
guard let object = try JSONSerialization.jsonObject(with: data) as? [[String: Any]] else { return nil }
guard let field1 = object[0]["field1_token"] as? [Any] else { return nil }
//do your thing
if let
way:
if let object = try JSONSerialization.jsonObject(with: data) as? [[String: Any]],
let field1 = object[0]["field1_token"] as? [Any] {
//do your thing
}
You may want to check Apple's article Working with JSON in Swift
Also you can use some of the json parsing/mapping libriaries like these:

serg_zhd
- 1,023
- 14
- 26
-1
Please replace let object : AnyObject
with let object : Any
.
Error showing because of wrong casting.

Amin Negm-Awad
- 16,582
- 3
- 35
- 50