4

I'm converting JSON data to a struct, then adding the struct to an array, but I'm having trouble accessing the values in the struct when I do so.

First I've got my struct:

struct Skill {
    var name: String

    init(dictionary: [String: Any]){
    name = dictionary["name"] as! String
    }    
}

Then in another class, I am converting my JSON data into the struct and adding it to an array. I can access the values within the for loop (ie skillDict.name), but I cannot access them from the array in another class.

var skillArray: NSMutableArray = []
fun getJSON(){
….
if let skill : NSArray = jsonRoot["skills"] as? NSArray
    {

        for each in skill{
            var skillDict = Skill(dictionary: each as! [String : Any])

            skillArray.add(skillDict)      
            }

    }

When I run the below code from another class, I get this error on the first print line:"this class is not key value coding-compliant for the key name". I've also tried using The second print line prints all of my objects correctly, but I cannot access the name value.

for each in skillArray{
       print(skillArray.value(forKey: "name"))
        print(each) //this line will print correctly, so I know the correct data is in the array

    }

I've also tried using the below code, both inside and outside of the for loop:

print(skillArray.map { $0["name"] as? String })

But I get a compiler error "Type Any has no subscript members"

How do I access the name value correctly?

0

4 Answers 4

2

You have two ways to fix it either make the skillArray of type [Skill] instead of NSMutablearray or cast $0 in map function to be of type Skill first and then use the underlying property.

e.g., This may be helpful:

print(skillArray.map { ($0 as! Skill).name })
Sign up to request clarification or add additional context in comments.

1 Comment

...and if you use flatMap { ($0 as? Skill).name } instead, it'll simply skip elements where the force cast fails instead of crashing
2

if you want to use subscript key isEqual to "name" then return name

struct Skill {
    var name: String

    init(dictionary: [String: Any]){
        name = dictionary["name"] as! String
    } 

    subscript(_ name: String) -> String? {
        get {
            return name == "name" ? self.name : nil
        }
    }
}

this code can use print(skillArray.map { $0["name"] as? String }) work

Comments

2

Instantiate the array as [Skill]:

var skills = [Skill]()
...
let names = skills.map { $0.name }

Comments

1

If you declare skillArray as:

var skillArray = Array<Skill>()

then this should work:

print(each.name)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.