简体   繁体   中英

Make Collection conform to custom protocol

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 { }

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 {}

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

extension Collection where Self: Occupiable { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM