Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve values from struct in swift

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?

like image 280
Wallboy Avatar asked Mar 09 '23 04:03

Wallboy


1 Answers

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 })
like image 121
NeverHopeless Avatar answered Mar 11 '23 17:03

NeverHopeless