[swift-users] Constraining the conforming type of a protocol

Ray Fix rayfix at gmail.com
Sun Jul 30 02:02:50 CDT 2017


Cool.  Thanks for your comment.  Done.  

https://bugs.swift.org/browse/SR-5581 <https://bugs.swift.org/browse/SR-5581>

Ray


> On Jul 29, 2017, at 5:55 PM, Slava Pestov <spestov at apple.com> wrote:
> 
> What you’re trying to do should be equivalent to this:
> 
> protocol Toggling : Equatable {
>> }
> 
> It’s a bug that placing the constraint on ‘Self’ does not have the same effect though; do you mind filing a JIRA?
> 
> Slava
> 
>> On Jul 29, 2017, at 12:24 PM, Ray Fix via swift-users <swift-users at swift.org <mailto:swift-users at swift.org>> wrote:
>> 
>> Hi,
>> 
>> I had a question about defining protocols. Originally I wrote:
>> 
>> protocol Toggling where Self: Equatable {
>>   static var all: [Self] { get }
>>   func toggled() -> Self
>>   mutating func toggle()
>> }
>> 
>> extension Toggling {
>> 
>>   func toggled() -> Self {
>>     let current = Self.all.index(of: self) ?? 0
>>     let next = (current + 1) % Self.all.count
>>     return Self.all[next]
>>   }
>> 
>>   mutating func toggle() {
>>     self = toggled()
>>   }
>> }
>> 
>> This resulted in a bunch of errors.  
>> 
>> Playground execution failed:
>>                          ^
>> error: Toggler.playground:7:28: error: cannot invoke 'index' with an argument list of type '(of: Self)'
>>     let current = Self.all.index(of: self) ?? 0
>>                            ^
>> 
>> Toggler.playground:7:28: note: expected an argument list of type '(of: Self.Element)'
>>     let current = Self.all.index(of: self) ?? 0
>> 
>> This approach worked:
>> 
>> 
>> protocol Toggling {
>>   static var all: [Self] { get }
>>   func toggled() -> Self
>>   mutating func toggle()
>> }
>> 
>> extension Toggling where Self: Equatable {
>> 
>>   func toggled() -> Self {
>>     let current = Self.all.index(of: self) ?? 0
>>     let next = (current + 1) % Self.all.count
>>     return Self.all[next]
>>   }
>> 
>>   mutating func toggle() {
>>     self = toggled()
>>   }
>> }
>> 
>> This version is probably better anyway but I am wondering if the first approach should have shown an error at the point of trying to attach the constraint to the protocol declaration.  Any insights on this?
>> 
>> Thank you,
>> Ray  Fix
>> 
>> 
>> 
>> 
>> _______________________________________________
>> swift-users mailing list
>> swift-users at swift.org <mailto:swift-users at swift.org>
>> https://lists.swift.org/mailman/listinfo/swift-users
> 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170730/9b429729/attachment.html>


More information about the swift-users mailing list