0

I'm trying this

struct Foo<T: Equatable> {
    let object: T
}


extension Array where Element == Foo { // this lines give me error tried Foo<T> but didn't work

    func updateElement(element: Element) {
        // Do the stuff
    }
}

And it's giving me error: Reference to generic type 'Foo' requires arguments in <...>

Any way to do this?

5
  • 1
    Foo<Int> and Foo<String> for instance are two completely different types so that why it doesn't work Commented Nov 18, 2020 at 14:44
  • @JoakimDanielson I understand both of them are different, that's why I want to specify Generic there, other wise I have to copy same code in all possible extension (e.g. Int, String, Float, etc.) Commented Nov 18, 2020 at 14:50
  • But they are different, Foo<Int> and Foo<String> are as different as Int and String are and that is why you can't just say Foo. Commented Nov 18, 2020 at 14:58
  • Related (duplicate?): Swift Conditional conformances with Generic Type. Commented Nov 18, 2020 at 15:16
  • @MartinR thanks it's related and answer to both of them seems same Commented Nov 18, 2020 at 16:05

2 Answers 2

2

What you need is to move the constrain from the extension to the method, create a generic Equatable type and add a where clause constraining the collection Element to Foo

extension Collection {
    func updateElement<T: Equatable>(element: Element) where Element == Foo<T> {

    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

@JoakimDanielson No you won't be able to mix different types of elements. This will require that all elements in the collection are one or another
There is no magic solution for this. I would consider a switch there an error of design. It all depends on the goal. I am assuming that OP needs to check them for equality. Anyway all OP might need if it is not the case is a custom protocol or protocol composition.
@JoakimDanielson I will use the Equatable protocol to compare stuff, I don't care what kind of object it is. Just want that object to implement Equatable.
@JoakimDanielson btw it's is not real implementation, was an example. where in updateElement i would find it in array and update it. I can't post my original code, it's just easiest example for my scenario. Sorry if my question was not clear
0

It looks like you can only create an extension for a specific type of Foo, like Foo<Int>. This works:

extension Array where Element == Foo<Int> { // this lines give me error tried Foo<T> but didn't work

    func updateElement(element: Element) {
        // Do the stuff
    }
}

1 Comment

I want T to be generic not Int or String, I updated my question, T is equatable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.