如何在Swift中仅删除整数数组中的相邻重复项? [英] How to remove only adjacent duplicates in an array of integers in Swift?

查看:121
本文介绍了如何在Swift中仅删除整数数组中的相邻重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的实现:

extension Array where Element:Equatable {
    func removeDuplicates() -> [Element] {
        var result = [Element]()

        for value in self {
            if result.contains(value) == false {
                let r = result.append(value)       
            }
        }
        return result
    }
}
let arrayOfInts = [1, 2, 2, 3, 3, 3, 1].reverse()
for element in arrayOfInts.removeDuplicates(){
    print(element)
}

我想在删除相邻整数之后对数组执行操作.

I would like to perform operations on the array after the adjacent integers have been removed.

推荐答案

可以通过将当前数组的元素添加到新数组中,但是仅在当前元素不等于要获取的最后一个元素时追加当前元素来解决此问题关心重复的相邻问题. 尝试此解决方案.

This can be simply solved by adding the elements of the current array to a new array but only appending the current element if it's not equal to the last element to take care of the duplicate adjacent problem. Try this solution.

extension Array where Element:Equatable {
func removeDuplicates()->[Element]{
    guard !self.isEmpty else { return [] }
    var noDuplicates = [Element]()

    for (index, element) in self.enumerated(){
        if index > 0{

            if element != noDuplicates.last{

                noDuplicates.append(element)
                   }
        }
        else{
            noDuplicates.append(element)
        }


    }

    return noDuplicates
}
}

同样,如果在反转数组后在ReversedCollection上使用此扩展名时遇到麻烦,那是因为Swift认为它与Array类型不同.一旦反转了Array,它就不再是数组,它将成为称为ReversedCollection的单独类型.如果要将此扩展名应用于ReversedCollection类型以及数组,则需要创建一个扩展名,该扩展名不仅限于数组,并且包括Reversed CollectionArray类型,或者将ReversedCollection转换为Array

Also if you're having trouble with using this extension on the ReversedCollection after you reverse the array it's because Swift recognizes it as being different from an Array type. Once you reverse an Array it no longer is an array it becomes a separate type called ReversedCollection. If you want to apply this extension to ReversedCollection types as well as arrays, you need to create an extension that's not limited to arrays and includes both Reversed Collection and Array types or convert the ReversedCollection into an Array

extension Collection where Element:Equatable {

let arrayOfInts = Array([1, 2, 2, 3, 3, 3, 1].reversed())
for element in arrayOfInts.removeDuplicates(){
    print(element)
}

这篇关于如何在Swift中仅删除整数数组中的相邻重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆