gpt4 book ai didi

Swift:运行时的泛型类型推断

转载 作者:行者123 更新时间:2023-11-28 06:24:46 26 4
gpt4 key购买 nike

看到奇怪的通用行为,这让我相信我在理解中遗漏了一些东西。

我正在使用以下方法循环抛出 JSON 响应并调用通用方法。 UserCardEcard都继承自IDObject,而IDObject又继承自Object(一个 Realm 类)

let props:[(label:String, type:IDObject.Type)] = [
(label: "deletedUsers", type: User.self),
(label: "deletedCards", type: Card.self),
(label: "deletedECards", type: Ecard.self)
]

for prop in props {
if let ids = json[prop.label].arrayObject as? [Int], ids.count > 0 {
DataManager.shared.delete(prop.type, ids: ids)
}
}

func delete<T:IDObject>(_ type:T.Type, ids:[Int]) {
guard ids.count > 0 else { return }
if let objectsToDelete = objects(type, where: NSPredicate(format: "identifier IN %@", ids)) {
delete(objectsToDelete)
}
}

func delete<T:Object>(_ objects:Results<T>) {
guard objects.count > 0 else { return }
do {
let realm = try Realm()
try realm.write {
realm.delete(objects)
}
} catch {
print(error)
}
}

delete(_ type:T.Type, ids:[Int]) 函数无法以这种方式推断泛型类型。

但是,展开 for prop in props 循环会按预期工作。

if let userIds = json["deletedUsers"].arrayObject as? [Int], userIds.count > 0 {
DataManager.shared.delete(User.self, ids: userIds)
}

泛型只在编译时起作用,还是有办法在运行时动态处理?

最佳答案

泛型在编译时被评估并分配一个单一的具体类型。没有“运行时类型推断”这样的东西。

我认为您想要的主要改变是:

func delete(_ type:IDObject.Type, ids:[Int]) {

您不想在 type 上特化此函数, 你只想传递 type .

不清楚是什么objects(_:where:)返回,所以这可能会破坏你的 delete方法。您可能需要使其不那么具体:

func delete(_ objects:Results<Object>) {

(这不是子类型化的 Elixir ;我假设 objects(_:where:) 准确返回 Results<Object>。)

关于Swift:运行时的泛型类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42304430/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com