问题描述
我有这个:
class Movies {
Name:String
Date:Int
}
和一系列 [电影].如何按名称的字母顺序对数组进行排序?我试过了:
and an array of [Movies]. How do I sort the array alphabetically by name? I've tried:
movieArr = movieArr.sorted{ $0 <$1 }
和
movieArr = sorted(movieArr)
但这不起作用,因为我没有访问 Movies 的 name 属性.
but that doesn't work because I'm not accessing the name attribute of Movies.
推荐答案
在传递给 sort
的闭包中,比较要作为排序依据的属性.像这样:
In the closure you pass to sort
, compare the properties you want to sort by. Like this:
movieArr.sorted { $0.name < $1.name }
或者在你想绕过案例的情况下:
or the following in the cases that you want to bypass cases:
movieArr.sorted { $0.name.lowercased() < $1.name.lowercased() }
旁注:通常只有类型以大写字母开头;我建议使用 name
和 date
,而不是 Name
和 Date
.
Sidenote: Typically only types start with an uppercase letter; I'd recommend using name
and date
, not Name
and Date
.
例如,在操场上:
class Movie {
let name: String
var date: Int?
init(_ name: String) {
self.name = name
}
}
var movieA = Movie("A")
var movieB = Movie("B")
var movieC = Movie("C")
let movies = [movieB, movieC, movieA]
let sortedMovies = movies.sorted { $0.name < $1.name }
sortedMovies
sortedMovies
将按顺序 [movieA, movieB, movieC]
Swift5 更新
channelsArray = channelsArray.sorted { (channel1, channel2) -> Bool in
let channelName1 = channel1.name
let channelName2 = channel2.name
return (channelName1.localizedCaseInsensitiveCompare(channelName2) == .orderedAscending)
这篇关于Swift:按字母顺序对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!