简体   繁体   中英

Extracting values from NSDictionary to individual variables

I really thought this was Xcode playing up as I can't for the life of me see what is causing this error in a fairly simple piece of Swift code but after restarting cleaning the project, restarting Xcode, and restarting my MacBook I'm still getting the same error.... But why!!??!!

Here is the code

// Loop through records saving them
for recordItem in records {
    if let record: NSDictionary = recordItem as? NSDictionary {                
        let time: String = record["time"] as! String
        let record: String = record["record"] as! String
        let recordId: String = record["record_id"] as! String
        let saveTime: String = record["save_time"] as! String
        let setId: String = record["set_id"] as! String

        // Does more stuff
    }
}

records is an NSArray and it is made from data downloaded from a remote server.

All is fine until the line beginning let recordId. This and the two lines below it are giving an error - Cannot subscript a value of type 'String' with an index of type 'String'

Why? And why is there no problem with the 2 lines above? And how do I fix it?

Any help is greatly appreciated as I'm at a bit of a dead end.

You are using the variable record to unwrap the optional recordItem but then you are re-assigning record as record["record"] - so from this point on it becomes a String, not a Dictionary - resulting in the error message Cannot subscript a value of type 'String' with an index of type 'String'

You just need to change one of the record variables

for recordItem in records {
    if let unwrappedRecord: NSDictionary = recordItem as? NSDictionary {
        let time: String = unwrappedRecord["time"] as! String
        let record: String = unwrappedRecord["record"] as! String
        let recordId: String = unwrappedRecord["record_id"] as! String
        let saveTime: String = unwrappedRecord["save_time"] as! String
        let setId: String = unwrappedRecord["set_id"] as! String

        // Does more stuff
    }
}

The problem is here, you are declaring record as a String , previously it was NSDictionary and due to scope the record in record["record_id"] is String not NSDictionary . Quick fix is to change the name as I did

    let time: String = record["time"] as! String
    let record1: String = record["record"] as! String
    let recordId: String = record["record_id"] as! String
    let saveTime: String = record["save_time"] as! String
    let setId: String = record["set_id"] as! String

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM