user
user

Reputation: 445

Error: Type 'Any' has no subscript members AlamoFire with Swift 4

I have tried many of solutions with no luck. I'm trying to pass my json data and return the users values.

Model:

import Foundation

class UserModel: NSObject {

var UserID: String!
var Name: String!

init(UserID: String, Name: String) {
    super.init()

    self.UserID = UserID
    self.Name = Name

}
}

Fetch Function:

    guard let url = URL(string: "https://api.com/api.php?PatientList") else { return }
    var request = URLRequest(url: url)

    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Accept")
    request.httpMethod = "POST"

    let pinPost = "&Token=\(token)"
    request.httpBody = pinPost.data(using: .utf8)

    Alamofire.request(request).responseJSON { (response) in
        if let dict = response.result.value as? Dictionary<String, AnyObject> {
            if let datas = dict["Data"] as? NSArray {
                for data in datas {

                    let users = UserModel(UserID: data["PatientID"], Name: data["DisplayName"])

                }
            }
        }
    }

I get a error message of Type 'Any' has no subscript members no previous solution has worked and I can't figure it out.

Image

 ["Response": 1, "Data": <__NSSingleObjectArrayI 0x600002624ae0>(
 <__NSArrayI 0x600002455f60>(
 {
DOB = "09/08/1987";
DisplayName = "Jesse Gray";
PatientID = "1575da84-864f-11e8-9bae-02bd535e30bc";
}

Upvotes: 0

Views: 235

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You need

if let datas = dict["Data"] as? [[String:Any]] {

instead of

if let datas = dict["Data"] as? NSArray {

as array elements are of type Any that can't be subscribted here data["PatientID"] and data["DisplayName"]

Alamofire.request("request").responseJSON { (response) in
    if let dict = response.result.value as? [String:Any] {
        if let datas = dict["Data"] as? [[String:Any]] {
            for data in datas {
                if let id = data["PatientID"] as? Int , let name = data["DisplayName"] as? String {
                  let users = UserModel(UserID:id, Name: name)
                } 
            }
        }
    }
}

Also consider using Codable to parse the response

struct Root: Codable {
    let data: [UserModel]
    enum CodingKeys: String, CodingKey {
       case data = "Data"
    }
}

struct UserModel: Codable {
    let patientID: Int
    let displayName: String

    enum CodingKeys: String, CodingKey {
        case patientID = "PatientID"
        case displayName = "DisplayName"
    }
}

Alamofire.request("request").responseData{ (response) in
    if let data = response.data  {

        do {
            let res = try JSONDecoder().decode(Root.self, from: data)
            print(res.data)
        }
        catch {
            print(error)
        }
    }
}

The correct is

{ "Data" : [{"DisplayName":"Jerry Smith","DOB":"09/08/1987"}] }

Upvotes: 2

Related Questions