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() }
Sidenote: Typically only types start with an uppercase letter; I'd recommend using name
and date
, not Name
and Date
.
Example, in a playground:
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
will be in the order [movieA, movieB, movieC]
Swift5 Update
channelsArray = channelsArray.sorted { (channel1, channel2) -> Bool in
let channelName1 = channel1.name
let channelName2 = channel2.name
return (channelName1.localizedCaseInsensitiveCompare(channelName2) == .orderedAscending)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…