[swift-users] How do you use protocol types?

Karl razielim at gmail.com
Wed Jul 13 20:58:49 CDT 2016


So I’m trying to work generically to construct things based on their conformance to a protocol with an initialiser. I’m sure this worked before; I’ve done it before. Maybe there have been some changes in the language or something, because I’ve tried everywhich-way and this just isn’t flying:

==================
protocol AProto {

	associatedtype ElementType
	func constructInstance(_: ElementType.Type) -> ElementType
}

protocol SimpleConstructableElement {
	init()
}

extension Int : SimpleConstructableElement {}

class Factory : AProto {

	typealias ElementType = SimpleConstructableElement

	func constructInstance(_ t: SimpleConstructableElement.Type) -> SimpleConstructableElement {
		return t.init()
	}
}

Factory().constructInstance(Int.self)
=================================

/tmp/MyPlayground.playground:15:7: Type 'Factory' does not conform to protocol 'AProto'
/tmp/MyPlayground.playground:6:7: Protocol requires function 'constructInstance' with type '(ElementType.Protocol) -> ElementType'
/tmp/MyPlayground.playground:19:7: Candidate has non-matching type '(SimpleConstructableElement.Type) -> SimpleConstructableElement’

=================================


The thing that gets me about this is that Xcode’s code-completion tells me that SimpleConstructableElement.Type is of type SimpleConstructableElement.Protocol, so it should be the same as ElementType.Protocol and should be accepted, right?

Karl


More information about the swift-users mailing list