更新时间:2023-01-12 22:07:35
可以通过将当前数组的元素添加到新数组中,但是仅在当前元素不等于要获取的最后一个元素时追加当前元素来解决此问题关心重复的相邻问题. 尝试此解决方案.
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 Collection
和Array
类型,或者将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)
}