Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AssociatedType in a protocol with typealias

Tags:

ios

swift

Lets say i have a protocol:

protocol Router {
    associatedtype Answer
    typealias AnswerCallback = (Answer) -> Void
}

At some point I want to store a variable of type AnswerCallback

var answerCallback: Router.AnswerCallback ...

But I need to specify which concrete type i'm using since i get this error:

Type alias 'AnswerCallback' can only be used with a concrete type or generic parameter base

How I can specify a type like Router.AnswerCallback ... where String is "Answer" type?

Instead the only way to work is to use var answerCallback: ((String) -> Void)

like image 651
Godfather Avatar asked Feb 06 '26 04:02

Godfather


1 Answers

You need a class/struct that conforms to Router, which has an Answer of String:

class StringRouter : Router {
    typealias Answer = String
}

let callback: StringRouter.AnswerCallback? = nil

If all you want is such a type alias, you don't need a protocol:

typealias AnswerCallback<T> = (T) -> Void
like image 154
Sweeper Avatar answered Feb 09 '26 02:02

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!