我有这个:
class Movies { Name:String Date:Int }
和[电影]数组。如何按名称的字母顺序对数组进行排序?我试过了:
movieArr = movieArr.sorted{ $0 < $1 }
和
movieArr = sorted(movieArr)
但这不起作用,因为我没有访问电影的名称属性。
在传递给的闭包中sort,比较要排序的属性。像这样:
sort
movieArr.sorted { $0.name < $1.name }
或以下要绕过案例的案例:
movieArr.sorted { $0.name.lowercased() < $1.name.lowercased() }
旁注: 通常,只有类型以大写字母开头;我建议使用nameand date,而不是Nameand Date。
name
date
Name
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]
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)