Reputation: 2537
I have an enum with associated types. All associated types conform a protocol. I want to reach a variable from that protocol without switching enum. How can I achieve this?
I want to get position
object from enum element without switch.
protocol ComponentModelProtocol {
var position: Int { get } //Describes in which stackview component will be. (0 means left, 1 means right)
var isTappable: Bool { get } //Adds gesture recognizer to the view If this is true
}
enum ComponentType {
case onelinetwolabel(content: LabelComponentModel)
case twolinelabel(content: BoxComponentModel)
case labelwithimage(content: BoxComponentModel)
case currencySelector(content: CurrencySelectorModel)
case seperator(position: Int)
}
struct CurrencySelectorModel: ComponentModelProtocol {
let position: Int
let isTappable: Bool
let currencyArray: [String]
}
struct LabelComponentModel: ComponentModelProtocol {
let key: String
let value: String
let position: Int
let isTappable: Bool
let labelType: OneLineTwoLabel.LabelType
init(key: String, value: String, position: Int, isTappable: Bool, labelType: OneLineTwoLabel.LabelType) {
self.key = key
self.value = value
self.position = position
self.isTappable = isTappable
self.labelType = labelType
}
init(key: String, value: String, position: Int) {
self.init(key: key,value: value,position: position, isTappable: false, labelType: .defaultLabel)
}
init(key: String, value: String, position: Int,isTappable: Bool) {
self.init(key: key,value: value,position: position, isTappable: isTappable, labelType: .defaultLabel)
}
}
//Struct for two line label component
struct BoxComponentModel: ComponentModelProtocol {
let key: String
let value: String
let position: Int
let isTappable: Bool
init(key: String, value: String, position: Int,isTappable: Bool) {
self.key = key
self.value = value
self.position = position
self.isTappable = isTappable
}
init(key: String, value: String, position: Int) {
self.init(key: key,value: value, position: position,isTappable: false)
}
}
I know I can do it with adding variable inside enum like below but It adds switch for every element. I'm looking for a more clever way If there is.
enum ComponentType: ComponentModelProtocol {
var position: Int {
switch self {
case .onelinetwolabel(content: let model):
return model.position
case .twolinelabel(content: let model):
return model.position
case .labelwithimage(content: let model):
return model.position
case .currencySelector(content: let model):
return model.position
case .seperator(position: let position):
return position
}
}
Upvotes: 1
Views: 201
Reputation: 4210
The other way to access the associated value is by the rather hideous (IMO 🙂) if case let
syntax.
I'm not sure it'll make things any easier so I'll not go into depth here, but all the info you'll need on it is on If Case Let syntax
Upvotes: 1