ios - Cannot subscript a value of type - Swift 3 -
i'm new swift , trying write application parse json webpage. i'm getting error "cannot subscript value of type '[dictionary]'"
how can fix this? occurs multiple times. following code. thanks!
func grabdata(results: [dictionary<string, any?>]){ guard let resultlist = results as? [dictionary<string, any?>] else { return } iresult in resultlist { var tempresult = searchresult() tempresult.studentid = self.getint(dict: [iresult], string: "studentid") tempresult.lastname = self.getstring(dict: [iresult], string: "lastname") tempresult.firstname = self.getstring(dict: [iresult], string: "firstname") tempresult.major = self.getstring(dict: [iresult], string: "major") tempresult.year = self.getstring(dict: [iresult], string: "year") tempresult.gpa = self.getdouble(dict: [iresult], string: "gpa") self.results.append(tempresult) } dispatchqueue.main.async { self.listtableview.reloaddata() } } func getstring(dict: [dictionary<string, any?>], string: string) -> string? { if let result = dict[dictionary<string, any?>] as? string { return result } return nil } func getint(dict: [dictionary<string, any?>], string: string) -> int? { if let result = dict[string] as? int { return result } return nil } func getdouble(dict: [dictionary<string, any?>], string: string) -> double? { if let result = dict[string] as? double { return result } return nil }
searchresult.swift
struct searchresult { let studentid: int let lastname: string let firstname: string let major: string let year: string let gpa: double init?(json: [string:anyobject]) { guard let studentid = json["studentid"] as? int else { return nil } guard let lastname = json["lastname"] as? string else { return nil } guard let firstname = json["firstname"] as? string else { return nil } guard let major = json["major"] as? string else { return nil } guard let year = json["year"] as? string else { return nil } guard let gpa = json["gpa"] as? double else { return nil } self.studentid = studentid self.lastname = lastname self.firstname = firstname self.major = major self.year = year self.gpa = gpa } }
viewcontroller.swift
func grabdata(json: [string:anyobject]) { guard let searchresult = searchresult(json) else { return } self.results.append(searchresult) dispatchqueue.main.async { self.listtableview.reloaddata() } }
this post helpful me when designing model interact rest api: https://developer.apple.com/swift/blog/?id=37
the structure of json makes difference.
for example:
[ { "studentid": 12345, "lastname": "smith" } ]
would represented [[string:anyobject]]
(an array of string , anyobject combinations)
if have this, need loop through , parse each element individually.
Comments
Post a Comment