gpt4 book ai didi

arrays - 在swift 3中对数组数组进行排序

转载 作者:搜寻专家 更新时间:2023-11-01 06:33:30 25 4
gpt4 key购买 nike

var myArray: [[String]] =
[
["1", "picture1.png", "John", "Smith"],
["2", "picture2.png", "Mike", "Rutherford"],
]

如何在第一项上对 myArray 进行排序?第二项?上升 ?下降?

非常感谢

最佳答案

我建议您创建一个structclass 来将这些相关数据打包在一起:

struct Person {
let id: Int
let picture: String // This should probably be a URL, NSImage or UIImage
let firstName: String
let lastName: String
}

然后用正确的类型定义你的实例(例如 id 是一个 Int,而不是一个 String 表示诠释

let people = [
Person(
id: 1,
picture: "picture1.png",
firstName: "John",
lastName: "Smith"
),
Person(
id: 2,
picture: "picture2.png",
firstName: "Mike",
lastName: "Rutherford"
),
]

从那里,您可以按照自己喜欢的方式对其进行排序:

people.sorted{ $0.id < $1.id }
people.sorted{ $0.id > $1.id }
people.sorted{ $0.picture < $1.picture }
people.sorted{ $0.picture > $1.picture }
people.sorted{ $0.firstName < $1.firstName }
people.sorted{ $0.firstName > $1.firstName }
people.sorted{ $0.lastName < $1.lastName }
people.sorted{ $0.lastName > $1.lastName }

关于arrays - 在swift 3中对数组数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44508958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com