swift - 访问结构中的结构以返回排序数组

标签 swift struct

我正在将数据从 JSON url 解析到我的用户对象,并尝试返回按名称字母顺序排序的对象。我在访问 Users 对象内的 names 属性时遇到问题。由于我的 JSON 的结构方式,我将我的结构嵌套在结构中。我想在我的 sortedList 数组中返回按名称字母顺序排序的数组。

     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()
}

最佳答案

为了排序目的,代码使用如下:

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

不需要 for 循环。

更新代码:

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()
}

关于swift - 访问结构中的结构以返回排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58677138/

相关文章:

c - C 中无需库的字符串连接

c - error C2071 非法存储类,在 C 中定义枚举类型

c - 构建并打印一个链表,其中每个节点代表 C 中的一个链表

ios - ios swift 中的 Linkedin 共享弹出窗口

ios - 我们可以更改 AlertController 按钮字体吗?

ios - 用其他自定义值替换零值

ios - Swift:我怎样才能有一个监听器来报告连接何时丢失以及何时恢复?

c# - 为什么我在 C# 中得到一个带有幻影类型的 "cycle in the struct layout"?

ios - 如何对 UIPageViewController 处理的页面内的容器进行动画处理,并且该动画与页面滑动(页面更改)相关?

c - 如何更改 FUNC 中结构的值?