Herakleis
Herakleis

Reputation: 533

Swift 3: Cannot invoke (protocol method) with argument list of type (generic)

Given this protocol:

import Foundation

protocol Updatable {
    associatedtype E

    func updateValuesWith(_ newElement: E)
}

And this implementation:

private func update<T: NSObject>(_ values: inout [T], with newValues: [T]) where T: Updatable {

    guard values.count != 0 else { values = newValues; return }

    for newElement in newValues {

        let newIndex = newValues.index(of: newElement)

        if values.contains(newElement) {

            let oldIndex = values.index(of: newElement)

            values[oldIndex!].updateValuesWith(newElement) //<--- PROBLEM HERE

            if oldIndex != newIndex {

                swap(&values[oldIndex!], &values[newIndex!])
            }
        } else {

            values.insert(newElement, at: newIndex!)
        }
    }

    for element in values where values.index(of: element)! > newValues.count {

        values.remove(at: values.index(of: element)!)
    }
}

I don't get why I am getting this error message

Cannot invoke 'updateValuesWith' with an argument list of type '(T)'

Expected an argument list of type '(T.E)'

on line values[oldIndex!].updateValuesWith(newElement).

After some unfruitful research I am convinced I must be missing something very basic but still can't figure out what exactly.

Enlighten me please?

Upvotes: 1

Views: 457

Answers (1)

Pavel Zdenek
Pavel Zdenek

Reputation: 7293

You are declaring input parameter type T to be Updatable, but your updateValuesWith does not take T. It takes another type E which you are not specifying at all. If you want your code to compile as is, you must tell the compiler what is E supposed to be:

... where T: Updatable, T.E == T

which is kinda strange because i have no idea how updateValuesWith knows what to do, when newElement does not implement any useful interface (except force casting it to what you expect it to be). But that would be a different question...

Upvotes: 1

Related Questions