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

Ray Fix rayfix at gmail.com
Sat Jul 29 14:23:04 CDT 2017


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




-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170729/84e526fe/attachment.html>


More information about the swift-users mailing list