var myArray: [[String]] =
[
["1", "picture1.png", "John", "Smith"],
["2", "picture2.png", "Mike", "Rutherford"],
]
如何在第一项上对myArray进行排序?第二项?上升 ?降序?在swift中对数组进行排序3
非常感谢
var myArray: [[String]] =
[
["1", "picture1.png", "John", "Smith"],
["2", "picture2.png", "Mike", "Rutherford"],
]
如何在第一项上对myArray进行排序?第二项?上升 ?降序?在swift中对数组进行排序3
非常感谢
通知,即指数范围没有被选中,有什么能在运行时会导致致命的错误。检查Alexanders的评论! :)
var myArray: [[String]] =
[
["1", "picture1.png", "John", "Smith"],
["2", "picture2.png", "Mike", "Rutherford"],
]
func sort<T: Comparable>(ArrayOfArrays: [[T]], sortingIndex: Int, sortFunc: (T, T) -> Bool)) -> [[T]] {
return ArrayOfArrays.sorted {sortFunc($0[sortingIndex], $1[sortingIndex])}
}
}
print(sort(ArrayOfArrays: myArray, sortingIndex: 0, sortFunc: <))
//[["1", "picture1.png", "John", "Smith"], ["2", "picture2.png", "Mike", "Rutherford"]]
print(sort(ArrayOfArrays: myArray, sortingIndex: 0, sortFunc: >))
//[["2", "picture2.png", "Mike", "Rutherford"], ["1", "picture1.png", "John", "Smith"]]
Swift的数组有一个内置的排序功能。只需调用它。
myArray[0].sort { $0.compare($1, options: .numeric) == .orderedAscending }
myArray[1].sort { $0.compare($1, options: .numeric) == .orderedDescending }
非常感谢你的帮助。 –
我建议你创建一个struct
或class
一起打包此相关的数据:
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
代表Int
。
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 }
非常感谢您的帮助。这很完美。 –
@BenoitDesruisseaux如果此答案满足您的问题,请将其标记为已接受 – Alexander
要使用数字字符串比较的数组进行排序(例如在项目的 “2” < “10”)在特定的index
:
let index = 1 // sort by second entry
myArray.sort { $0[index].compare($1[index], options: .numeric) == .orderedAscending }
如果你不需要数字比较(例如,其中 “10” < “2”):
myArray.sort { $0[index] < $1[index] }
正如其他人指出的,尽管如此,您应该使用自定义struct
或class
的数组,而不是将您的对象表示为单纯的字符串数组。
非常感谢您的帮助。 –
如果您使用结构或类将相关数据打包为自包含的实例,那么您将有更容易的时间。 – Alexander
建议使用'struct'或'class'来代表该数组中的属性,如索引(我猜这就是1或2的意思),pictureName,Name,FamilyName,而不是使用字符串数组。 – Larme
非常感谢您的帮助。 –