不能在下标中使用索引

时间:2017-12-02 14:55:59

标签: arrays swift indexing

我不知道为什么我不能使用下标中的索引来检索数组中的对象。

我收到了这个错误:

参数类型'@lvalue MPMediaItem'不符合预期类型'序列'

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
    }
}

1 个答案:

答案 0 :(得分:1)

compareDateAndTime()

无法编译,因为 result += self[index] 会将元素序列附加到 数组(如另一个数组)。要附加单个元素,请使用

+=

备注:您的方法的更紧凑的实现将是(未经测试!)

 result.append(self[index])