0

I want to add a generic parameter for all collection type that has isEmpty so they can also have isNotEmpty When I try to make Collection conform to Occupiable I got an compile error

error here : Extension of protocol 'Collection' cannot have an inheritance clause

also String conform to a protocol that inherent from Array so can we just remove extension String: Occupiable { } once we found a solution for the issue above ?

// Anything that can hold a value (strings, arrays, etc)
protocol Occupiable {
    var isEmpty: Bool { get }
    var isNotEmpty: Bool { get }
}

// Give a default implementation of isNotEmpty, so conformance only requires one implementation
extension Occupiable {
    var isNotEmpty: Bool {
        return !isEmpty
    }
}

extension String: Occupiable { }

//  error here : Extension of protocol 'Collection' 
//  cannot have an inheritance clause
extension Collection: Occupiable { }
iOSGeek
  • 5,115
  • 9
  • 46
  • 74
  • You might find the answer here: https://stackoverflow.com/questions/41993616/swift-is-it-possible-to-add-a-protocol-extension-to-a-protocol – Yevgeniy Leychenko Oct 26 '18 at 12:11

2 Answers2

0

Here you have created Occupiable protocol with isEmpty and isNotEmpty variables so when we implement protocol in any class these two variable need to declare to fullfill protocol. but here you already declare isNotEmpty variable inside Occupiable's extension so now only one isEmpty compulsory in class where we implement protocol. so isEmpty inside Collection Protocol so we need to extend protocal. but it work in String because string is struct .
you need to code for Collection like:

extension Collection where Self : Occupiable {}
Jatin Kathrotiya
  • 539
  • 3
  • 12
  • It does not work, now when try to used to Dictionary I get `Value of type '[String : Any]' has no member 'isNotEmpty'; did you mean 'isEmpty'?` – iOSGeek Oct 26 '18 at 14:54
0

You need to set a constraint on conformance. This will fix the error.

extension Collection where Self: Occupiable { }
  • It does not work, now when try to used to Dictionary I get `Value of type '[String : Any]' has no member 'isNotEmpty'; did you mean 'isEmpty'?` – iOSGeek Oct 26 '18 at 14:54