iPadawan
iPadawan

Reputation: 1110

swift5 - enum protocol - Self and self and a variable

I like to separate soms function and var from a enum and thought this was a way. (Just sample code) This results in a compile error "Type 'Self' has no member 'allCases'"

public protocol EnumFunctions: Hashable {
    static var numOfCases: Self { get }
}

public extension EnumFunctions {
    static var numOfCases: Self {
        return self.allCases.count
    }
}

my Enum Cooking Timer

public struct Cook_Time {
    // struct naming for the dump command like
    // dump(Cook_Time(), name: Cook_Time().structname)

    let structname : String = "Cook_Time"
    let a = "a"
    let allValues = PFTime.allValues

    public enum PFTime : String , CaseIterable, EnumFunctions {
        case t1m = "1mim"
        case t3m = "3min"
        case t5m = "5min"
        case t10m = "10min"
        ....

        static let allValues = PFTimer.allCases.map { $0.rawValue }
    }

}

How can I fix this? what is my false mind setting about this? I do need Self instead of self, rigth?

Also if I make an extension for PFTime, in a separated file, why does I get the error "Cannot find type 'PFTime' in scope"?

Upvotes: 1

Views: 789

Answers (1)

gcharita
gcharita

Reputation: 8327

In order to access allCases property of CaseIterable protocol, you need to change your EnumFunctions protocol to something like this:

public protocol EnumFunctions: Hashable, CaseIterable {
    static var numOfCases: Int { get }
}

public extension EnumFunctions {
    static var numOfCases: Int {
        return allCases.count
    }
}

Also you can create an extension to PFTime just by adding Cook_Time. as prefix because PFTime is placed inside Cook_Time struct:

extension Cook_Time.PFTime {
    
}

Upvotes: 1

Related Questions