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?
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 })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With