Removing duplicate elements from an array in Swift

后端 未结 30 2006
遥遥无期
遥遥无期 2020-11-22 00:07

I might have an array that looks like the following:

[1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]

Or, reall

30条回答
  •  盖世英雄少女心
    2020-11-22 00:56

    This is just a very simple and convenient implementation. A computed property in an extension of an Array that has equatable elements.

    extension Array where Element: Equatable {
        /// Array containing only _unique_ elements.
        var unique: [Element] {
            var result: [Element] = []
            for element in self {
                if !result.contains(element) {
                    result.append(element)
                }
            }
    
            return result
        }
    }
    

提交回复
热议问题