【问题标题】:Wrong swift extension function is called调用了错误的 swift 扩展函数
【发布时间】:2022-06-22 19:40:25
【问题描述】:

当视图调用getBadge()方法时,如果Status.self在运行时是OpenAccessPointState,为什么它使用扩展中的函数没有Status == OpenAccessPointState条件?

代码如下:

protocol BadgeStateViewRepresentable: Statusable {
    func getBadge() -> BadgeWithText?
}

protocol Statusable {
    associatedtype Status: AccessPointState
    var status: Status { get }
}

extension View where Self: BadgeStateViewRepresentable {
    func getBadge() -> BadgeWithText? {
        return nil
    }
}

extension View where Self: BadgeStateViewRepresentable, Status == OpenAccessPointState {
    func getBadge() -> BadgeWithText? {
        return BadgeWithText()
    }
}

struct SomeDeviceDetailsView: View, BadgeStateViewRepresentable {
    var status: some AccessPointState {
        return OpenAccessPointState()
    }


    var body: some View {
        getBadge()
    }
}

有没有办法让它工作?

【问题讨论】:

    标签: ios swift swiftui protocols


    【解决方案1】:

    如果您确实显式声明了status 的类型,那么它会按预期工作:

    var status: OpenAccessPointState {
        return OpenAccessPointState()
    }
    

    这是因为不透明类型是不透明的。 SomeDeviceDetailsView.Statussome AccessPointState,您无法“看穿”具体的 AccessPointState 是什么。所以不满足Status == OpenAccessPointState的要求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多