soRazor
soRazor

Reputation: 147

Access a struct within a struct to return a sorted array

I am parsing data to my Users object from a JSON url and attempting to return the object sorted alphabetically by names. I am having trouble accessing the names property inside of my Users object. I have nested my struct inside of a struct because of the way my JSON is structured. I would like to return the array sorted alphabetically by names in my sortedList array.

     struct Response: Codable
 {
struct Users: Codable {
    var fullName :String
    var biography:String

    enum CodingKeys: String, CodingKey {
        case fullName = "full_name"
        case biography
    }
}

var users:[Users]
}


//   let sortedList = Response{ $0.fullName < $1.fullName }
//Cannot invoke initializer for type 'Response' with an argument list of type '((_, _) -> _)'


func parse(){
    guard let url = URL(string: "samplePage.json") else {return}
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let dataResponse = data,
            error == nil else {
                print(error?.localizedDescription ?? "Error")
                return }
        do{

            let response = try! JSONDecoder().decode(Response.self, from: dataResponse)
            for user in response.users{
                print(user.fullName)
                print(user.biography)
             let sortedArr = user.fullName.sorted{ $0.fullName < $1.fullName }
                //Value of type 'Character' has no member 'fullName'
            }
        } catch let parsingError {
            print("Error", parsingError)
        }
    }
    task.resume()
}

Upvotes: 0

Views: 43

Answers (1)

SGDev
SGDev

Reputation: 2252

For sorting purpose code use like this :

let sortedArr = response.users.sorted{ $0.fullName < $1.fullName }

no need for for loop.

updated code:

func parse(){
    guard let url = URL(string: "samplePage.json") else {return}
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in

    guard let dataResponse = data,
        error == nil else {
            print(error?.localizedDescription ?? "Error")
            return }
    do{

        let response = try! JSONDecoder().decode(Response.self, from: dataResponse)
        for user in response.users{
            print(user.fullName)
            print(user.biography)
        }
        // use code like this 
        let sortedArr = response.users.sorted{ $0.fullName < $1.fullName }
    } catch let parsingError {
        print("Error", parsingError)
    }
}
task.resume()
}

Upvotes: 1

Related Questions