General parameter cannot be displayed

I am writing an Array extension for individual elements

extension Array {
    func distinct<T: Equatable>() -> [T]{
        var unique = [T]()
        for i in self{
            if let item = i as? T {
                if !unique.contains(item){
                    unique.append(item)
                }
            }
        }
        return unique
    }
}

And try calling this function as below

let words = ["pen", "Book", "pencile", "paper", "Pin", "Colour Pencile", "Marker"]
words.distinct()

But it gives the error "general parameter" T "cannot be output fast"

+4
source share
1 answer

You can get rid of this error by telling the compiler what you expect:

let a: [String] = words.distinct()

The problem is that the compiler does not know what generic T. is. It would be much better to tell the compiler that you define a specific function for all arrays, where their Element is Equableable:

extension Array where Element : Equatable {
    func distinct() -> [Element]{
        var unique = [Element]()
        for i in self{
            if let item = i as? Element {
                if !unique.contains(item){
                    unique.append(item)
                }
            }
        }
        return unique
    }
}
+14
source

Source: https://habr.com/ru/post/1627937/


All Articles