符合单一协议的 Swift Enum 关联值

发布于 2025-01-16 23:16:15 字数 529 浏览 5 评论 0原文

如何获取当前枚举案例的关联值作为可刷新而不使用详尽的开关? 在情况下,我只需要将其作为协议检索,该协议用于每种情况相关类型。

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦屿孤独相伴 2025-01-23 23:16:15

我已经找到了解决方案,以防有人也需要这个。

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

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
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文