我正在尝试将帖子数组中的底部帖子移动到帖子数组的顶部。我创建了以下代码:
self.posts.insert(contentsOf: tempPosts, at: 0)
let element = self.posts.remove(at: tempPosts.endIndex)
self.posts.insert(element, at: 0)
let newIndexPaths = (0..<tempPosts.count).map { i in
return IndexPath(row: i, section: 0)
}
此代码给出错误:代码块第二行的索引超出范围。
我尝试了相同的代码来移动元素,但我用tempPosts.endIndex - 1
替换了tempPosts.endIndex
。这可以将数组中倒数第二个帖子移动到顶部。但是当我将代码改回tempPosts.endIndex
时,它不会将底部的帖子移动到数组的顶部。
我尝试添加 if 语句:
if self.posts.count > 2 {
let element = self.posts.remove(at: tempPosts.endIndex)
self.posts.insert(element, at: 0)
}
但我得到了同样的致命错误。
我的代码中出了什么问题,如何解决它?
如果您的目的是将集合的最后一个元素移动到它的开头,则可以插入removeLast
方法返回的结果元素。只要确保如果数组为空,则不要调用此方法:
posts.insert(posts.removeLast(), at: 0)
您还可以扩展RangeReplaceableCollection
并创建自定义方法,如下所示:
extension RangeReplaceableCollection where Self: BidirectionalCollection {
mutating func moveLastElementToFirst() {
insert(removeLast(), at: startIndex)
}
}
var test = [2,3,4,5,6,7,8,9,1]
test.moveLastElementToFirst()
test // [1, 2, 3, 4, 5, 6, 7, 8, 9]
var string = "234567891"
string.moveLastElementToFirst()
string // "123456789"