我不知道为什么不能使用下标中的索引来检索数组中的对象。
我得到这个错误:
参数类型“@lvalue mpmediatem”不符合预期的类型“Sequence”
extension Array where Element == MPMediaItem {
mutating func alignToProb(songIDWithNumberOfPick: [Int: Int]){
let sortedDict = songIDWithNumberOfPick.sorted{ $0.value > $1.value }
var result = [MPMediaItem]()
for (songID, numberOfPick) in sortedDict {
if let index = self.index(where: { $0.songID == songID }) {
result += self[index] // this line I got error. // Argument type '@lvalue MPMediaItem' does not conform to expected type 'Sequence'
}
}
self = result
}
}
最佳答案
result += self[index]
不编译,因为
+=
将元素序列附加到数组(例如另一个数组)。要附加单个元素,请使用
result.append(self[index])
备注:一个更紧凑的方法实现将是(未测试的!)
extension Array where Element == MPMediaItem {
mutating func alignToProb(songIDWithNumberOfPick: [Int: Int]){
let sortedIDs = songIDWithNumberOfPick.sorted{ $0.value > $1.value }.map { $0.key }
let result = sortedIDs.flatMap { songID in
first(where: { $0.songID == songID })
}
self = result
}
}