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@swift.org https://lists.swift.org/mailman/listinfo/swift-users