Search code examples
swiftenumsprotocolsassociated-types

Swift Enum associated values conforming to single protocol


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
    }
}

Solution

  • 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
            (caseReflection as? Refreshable)?.refresh() //If associated type doesn't have label
            
            let refreshable = Mirror(reflecting: caseReflection).children.first?.value as? Refreshable
            refreshable?.refresh() //If associated type has label
        }
    }