Cannot subscript a value of type 'JSON' with an index of type 'STRING'
Asked Answered
C

1

8

This was working in Swift2 but now in Swift3 (after automatic conversion) I'm getting an error:

if self.entry["scheduler"] || self.entry["owner"]

Cannot subscript a value of type 'JSON' with an index of type 'STRING'

The values of self.entry["scheduler"] etc. are boolean but I think the issue is the indices, "scheduler" and "owner"

Of course, I reference other indices of self.entry in the exact same way and get no error when I build.

xcode auto updated and I am living in a nightmare.

Chisel answered 6/11, 2016 at 14:51 Comment(0)
B
16

Substitute whatever type you're expecting for the .string in the first two lines

let scheduler = self.entry["scheduler"].string
let owner = self.entry["owner"].string

if(scheduler != nil || owner != nil)
{
    // Take care here - scheduler and owner are both optionals
}
Benumb answered 9/11, 2016 at 16:27 Comment(1)
Additionally you can use a library like SwiftyJSON to solve this in more generic way. It provides you facility to case data to int, bool and other data types as well. responseBody["driver_profile"]["name"].stringValue , responseBody["driver"]["age"].intValue For more details, github.com/SwiftyJSON/SwiftyJSON Furthermore those methods depend on your Swift and Package versions.Shabbir

© 2022 - 2024 — McMap. All rights reserved.