[swift-evolution] [Draft] Introducing StaticSelf, an Invariant Self

Vladimir.S svabox at gmail.com
Sat May 14 02:34:48 CDT 2016


Hmm.. very interesting..

@Matthew, is the code below looks like the same as you wanted to achieve 
with `->StaticSelf` ?

protocol Makable {
     associatedtype MadeType
     func make(value: Int) -> MadeType
}

class A {

}

class B: A {
     func make(value: Int) -> B {
         return B()
     }
}

class C : B {
     override func make(value: Int) -> B {
         return C()
     }
}


extension B : Makable {
     typealias MadeType = B
}

func makeWithZero<T: Makable>(creator t: T) -> T.MadeType {
     return t.make(0)
}

var instance : B = C()

print(instance.make(0)) // main.C
print(makeWithZero(creator: instance))  // main.C



On 14.05.2016 8:55, Nicola Salmoria via swift-evolution wrote:
> Matthew Johnson via swift-evolution <swift-evolution at ...> writes:
>
>> I agree it’s a bit tricky.  But that’s better than not possible at all.
>  You just need a typealias and a same type constraint to make this work as
> expected / desired:
>>
>>
>> protocol Makable {
>>
>> 	typealias RootMakable = StaticSelf
>> 	static func make(value: Int) -> StaticSelf
>> }
>>
>> func makeWithZero<T: Makable where T == T.RootMakable>(x: Int) -> T {
>> 	return T.make(value: 0) // works now
>>  }
>>
>>
>> Now that we have a typealias we can refer to the binding of StaticSelf and
> constrain it as necessary for whatever purpose we have in mind.  In some
> cases that will be a same type constraint so that our code works properly
> with class clusters.  I don’t have concrete examples of other use cases but
> can imagine use cases constraining the typealias to a protocol, for example.
>
> You can do that today:
>
> protocol Makable {
>     associatedtype MadeType
>     static func make(value: Int) -> MadeType
> }
>
> func makeWithZero<T: Makable where T == T.MadeType>(x: Int) -> T {
>     return T.make(value: 0)
> }
>
> You can't currently constrain MadeType to be the same as the conforming
> type, but, does it matter? What kind of extra guarantees would that give,
> since you need to add the extra constraint anyway in generic code?
>
> Nicola
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>


More information about the swift-evolution mailing list