You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift封装ObjectBox时,如何让编译器认可对象符合指定协议?

ObjectBox数据库抽象层泛型约束问题

我正在实现一个抽象层,用于在应用中隐藏ObjectBox数据库的具体实现细节,当前代码实现如下:

class ObjectBoxDatabase: Database {
 
    func all<T>(of type: T.Type) throws -> [T] where T : DatabaseEntity {
        let box = self.getBox(for: T.self)
        return box?.all() ?? []
    }

    private func getBox<T>(for type: T.Type) -> Box<T>? where T : DatabaseEntity {
       switch T.self {
        case is SomeEntity.Type:
            return someEntityBox as? Box<T>
        case is SomeOtherEntity.Type:
            return someOtherEntityBox as? Box<T>
        default:
            return nil
        }
    }
}

目前getBox只是占位实现,我计划理清泛型逻辑后再补充更复杂的逻辑,但调用getBox时编译器报错,要求T必须同时符合__EntityRelatable、EntityInspectable协议,且满足T.EntityBindingType.EntityType == T。Box的泛型约束定义如下:

Box<E> : CustomDebugStringConvertible where E : ObjectBox.EntityInspectable, E : ObjectBox.__EntityRelatable, E == E.EntityBindingType.EntityType

我原本以为单个约束可以通过类型转换解决,但这三个约束互不相关,不知道怎么把T转换为同时符合这三个约束和DatabaseEntity的类型。

我还考虑过不让getBox返回Box<T>,转而返回其他通用类型来规避约束限制,但始终找不到合适的类型。最后尝试让DatabaseEntity协议符合所有上述约束,返回Box<DatabaseEntity>,但还是报错:“any DatabaseEntity does not conform EntityInspectable”。

补充说明

  • someEntityBox和someOtherEntityBox分别是Box<SomeEntity>和Box<SomeOtherEntity>类型,这些实体都符合ObjectBox的Entity协议。
  • DatabaseEntity目前只是一个空协议,定义如下:
protocol DatabaseEntity {} 

内容的提问来源于stack exchange,提问作者Krisztian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 23:55:01