我正在将数据从 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/