How should I implement Default Associated Values with Swift Enums?

前端 未结 3 1350
没有蜡笔的小新
没有蜡笔的小新 2021-02-20 09:27

Swift question is there a way of having an enum type with one case that can have an associated value.

I have an API that gives me available filters, it\'s unlikely but p

相关标签:
3条回答
  • 2021-02-20 09:47

    According to this answer: Default value for Enum in Swift

    I recommend using such an approach

    public enum Result {
        case passed(hint: String)
        case failed(message: String)
    
        static let passed: Self = .passed(hint: "")
    }
    
    
    let res: Result = Result.passed
    
    0 讨论(0)
  • 2021-02-20 09:54

    Extending Nathan Perry's response:

    You can add a

    var underlyingString: String {
      return getUnderlyingString(self) 
    }
    

    to the enum. Then define

    func getUnderlyingString(apiFilter: APIFilters) -> String { 
        switch apiFilter {
        case .Default(let defaultAPIFilter):
            return defaultAPIFilter.rawValue
        case .Custom(let custom):
            return custom
        }
    }
    
    0 讨论(0)
  • 2021-02-20 09:59

    I know this is a bit old, but would this work for what you want?

    typealias FilterIdentifier = String
    
    enum DefaultAPIFilters: FilterIdentifier {
        case Everyone = "everyone"
        case Team = "team"
    }
    
    enum APIFilters {
        case Default(DefaultAPIFilters)
        case Custom(FilterIdentifier)
    }
    
    let everyoneFilter = APIFilters.Default(.Everyone)
    let teamFilter = APIFilters.Default(.Team)
    let clownFilter = APIFilters.Custom("clowns_only")
    
    0 讨论(0)
提交回复
热议问题