How should I implement Default Associated Values with Swift Enums? -
swift question there way of having enum type 1 case can have associated value.
i have api gives me available filters, it's unlikely possible api add additional filter types. if api sends unknown filter type want keep information associated enum.
below different ideas had doing this.
my first 2 tries didn't compile. third try feels bit clunky.
does have better way of doing this? think shouldn't use enum problem?
typealias apifilteridentifier = string /* not compile */ enum enumtestassociatedvaleu: apifilteridentifier { case unknown(apifilteridentifier) case = "everyone" case team = "myteam" } /* not compile */ enum enumtestdefaultassociatedvalues: apifilteridentifier { case unknown(apifilteridentifier) case everyone(apifilteridentifier = "everyone") case team(apifilteridentifier = "myteam") } /* compiles there better way? */ enum enumtestwithcustominit { case unknown(apifilteridentifier) case case team init(filteridentifier: apifilteridentifier) { let everyone: apifilteridentifier = enumtestwithcustominit.everyonefilteridentifier let team: apifilteridentifier = enumtestwithcustominit.teamfilteridentifier switch filteridentifier { case everyone: self = .everyone case team: self = .team default: self = .unknown(filteridentifier) } } func asidentifer() -> apifilteridentifier { switch self { case .everyone: return enumtestwithcustominit.everyonefilteridentifier case .team: return enumtestwithcustominit.teamfilteridentifier case .unknown(let filteridentifier): return filteridentifier } } private static var everyonefilteridentifier: apifilteridentifier { return "everyone" } private static var teamfilteridentifier: apifilteridentifier { return "myteam" } }
i know bit old, work want?
typealias filteridentifier = string enum defaultapifilters: filteridentifier { case = "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")
Comments
Post a Comment