Home > Net >  Swift Enum associated values conforming to single protocol
Swift Enum associated values conforming to single protocol

Time:03-24

How can I get associated value of current enum's case as Refreshable not using exhaustive switch? In condition I only need it retrieved as protocol, which is used for each case associated type.

class Type1: Refreshable {}
class Type2: Refreshable {}
class Type3: Refreshable {}

protocol Refreshable {
    func refresh()
}

enum ContentType {
    case content1(Type1 & Refreshable)
    case content2(Type2 & Refreshable)
    case content3(Type3 & Refreshable)
    
    func refreshMe() {
        //self.anyValue.refresh() //Want simple solution to get to the refresh() method not knowing actual current state
    }
}

CodePudding user response:

I've found the solution in case anyone will need this too.

enum ContentType {
    case content1(Type1 & Refreshable)
    case content2(Type2 & Refreshable)
    case content3(someLabel: Type3 & Refreshable)
    
    func refreshMe() {
        let caseReflection = Mirror(reflecting: self).children.first!.value
        let refreshable = Mirror(reflecting: caseReflection).children.first?.value as? Refreshable
        
        (caseReflection as? Refreshable)?.refresh() //If associated type doesn't have label
        refreshable?.refresh() //If associated type has label
    }
}

CodePudding user response:

If you need the enum, then making computed properties on it is common for extracting the associated values

enum ContentType {
    case content1(Type1 & Refreshable)
    case content2(Type2 & Refreshable)
    case content3(Type3 & Refreshable)

    var refreshable: Refreshable {
        switch self {
        case let .content1(r):
            return r
        case let .content2(r):
            return r
        case let .content3(r):
            return r
        }
    }

    func refreshMe() {
        refreshable.refresh() // Want simple solution to get to the refresh() method not knowing actual current state
    }
}
  • Related