简体   繁体   中英

AssociatedType in a protocol with typealias

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM