[swift-users] Protocol associated type constraints in classes and structs ?

Trevör ANNE DENISE trevor.annedenise at icloud.com
Fri Feb 10 10:46:20 CST 2017


Hello everyone !

I am currently writing a project where I would like to do something similar to this:

protocol ProtocolA {
    associatedtype U
    var someVariable : U { get set }
    func someFunction(_ x:U) -> U
}

class SomeClass<T> {
    var someProperty : ProtocolA where ProtocolA.U == T
}

But this isn't possible so I had to implement it as a generic class:
class NewClass<U> { ... }

And now I am using it like this:
class SomeClass<T> {
	var someProperty: NewClass<T>
}

The issue here is that protocols aren't used any more with this approach, and in my case there is no "default" implementation of myFunction, so protocols where really useful!!

Is there a better way to do that in the current Swift version?

Today, I came across the proposal SE-0142 (Permit where clauses to constrain associated types), but this only seems to apply inside of protocols, what is your opinion about having similar mechanisms in classes and structs ?

Thank you!

Trevör
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170210/7811c668/attachment.html>


More information about the swift-users mailing list