我有一个带有多个值的2D数组。
此数组上的一个字段称为group
,让我们想象一下我的数组具有以下顺序:
private var myArray = [
ArrayModel(
id: 0,
name: "Test",
color: 0,
img: "img.png",
group = "myGroup"),
ArrayModel(
id: 1,
name: "Test1",
color: 0,
img: "img.png",
group: "myGroup"),
ArrayModel(
id: 2,
name: "Test2",
color = 0,
img = "img.png",
group = "myGroup3")
ArrayModel(
id: 3,
name: "Test3",
color: 0,
img: "img.png",
group: "myGroup2"),
ArrayModel(
id: 4
name: "Test4"
color: 0
img: "img.png"
group: "myGroup3")
]
class ArrayModel: Decodable {
var id: Int
var name: String
var color: Int
var img: String
var group: String
convenience init() {
self.init()
id = 0
name = ""
color = 0
img = ""
group = ""
}
init(id: Int, name: String, color: Int, img: String, group: String) {
self.id = id
self.name = name
self.color = color
self.img = img
self.group = group
}
}
如何将myArray[2]
移到myArray[1]
中?
let myArray = [
ArrayModel(
id: 0,
name: "Test",
color: 0,
img: "img.png",
group: "myGroup")
]
[1] => same shema, but group => "myGroup"
[2] => same shema, but group => "myGroup2"
[3] => same shema, but group => "myGroup2"
[4] => same shema, but group => "myGroup3"
]
我尝试过这个:
myArray.sorted(by: { $0.group < $1.group })
感谢您的帮助!
答案 0 :(得分:1)
这可能有助于您按区分大小写进行排序,但是您的myArray
应该是mutable
。例如:var myArray
myArray = myArray.sorted(by: { $0.group.localizedCompare($1.group) == .orderedAscending})
答案 1 :(得分:1)
尝试一下:
myArray.sort { $0.group < $1.group }
.sort(by: ...)
不是您所需要的,因为您想修改 myArray
(通过排序)。为此,您必须省略by:...
。
有关更多信息,请参见this answer:)