0

I am using Swift 4 and looking for a way to create extension function for array collection with arguments of type

typealias Listener<T> = (T) -> Void

however extension below cannot be created (Use of undeclared type 'T')

extension Sequence where Element == Listener<T>{
    func callAll(t: T){
        self.forEach { $0(t) }
    }
}

Is there a way to make it work?

1
  • 2
    This can be some hint for you. Commented Oct 24, 2017 at 20:56

1 Answer 1

5

You cannot introduce new generic parameters at the header of an extension like T in your code, but each method can have generic parameters.

typealias Listener<T> = (T) -> Void

extension Sequence {
    func callAll<T>(t: T)
        where Element == Listener<T>
    {
        self.forEach { $0(t) }
    }
}
let listeners: [Listener<Int>] = [
    { print($0) },
    { print($0 * 2) },
]

listeners.callAll(t: 2)
Sign up to request clarification or add additional context in comments.

1 Comment

simple solution so I mark it as an answer, thank you

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.