gpt4 book ai didi

swift - 在数组中使用 PAT 存储通用结构的一些问题

转载 作者:行者123 更新时间:2023-11-30 10:33:15 24 4
gpt4 key购买 nike

我有一个适用于任何类型的可比较模型的简单协议(protocol):

protocol PSDiffableModelProtocol: Hashable {
var identifier: UUID { get }
}

extension PSDiffableModelProtocol {
func hash(into hasher: inout Hasher) { hasher.combine(identifier) }

static func == (lhs: Self, rhs: Self) -> Bool { lhs.identifier == rhs.identifier }
}

实际上实现该协议(protocol)的结构:

struct PSModel1: PSDiffableModelProtocol, Decodable {
let identifier = UUID()
let title: String
let subtitle: String
let additionalSubtitle: String
let imageUrl: URL
let footnote: String?
}

struct PSModel2: PSDiffableModelProtocol, Decodable { /* ... */ }

// ....

每个模型必须存储在另一个可比较模型中:

struct PSSection<Model: PSDiffableModelProtocol>: PSDiffableModelProtocol {
let identifier = UUID()
let title: String?
let subtitle: String?
let models: [Model]
}

然后有一个简单的问题,但是如何将我的部分存储在一个地方?像这样:

var sections: [PSSection] = [
PSSection(..., models: [PSModel1(...), PSModel1(...), ]),
PSSection(..., models: [PSModel2(...), PSModel2(...), ]),
// ...
]

最佳答案

您无法存储 [PSSection],因为编译器应该在编译时而不是运行时知道泛型类型。

最优选的方法是使用类型删除

protocol PSDiffableModelProtocol: Hashable {
var identifier: UUID { get }
}

extension PSDiffableModelProtocol {
func hash(into hasher: inout Hasher) { hasher.combine(identifier) }

static func == (lhs: Self, rhs: Self) -> Bool { lhs.identifier == rhs.identifier }
}

struct TodayModel1: PSDiffableModelProtocol, Decodable {
let identifier = UUID()
let title: String
let subtitle: String
let additionalSubtitle: String
let imageUrl: URL
let footnote: String?

init() {
title = ""
subtitle = ""
additionalSubtitle = ""
imageUrl = URL(fileURLWithPath: "")
footnote = ""
}
}

struct TodayModel2: PSDiffableModelProtocol, Decodable {
var identifier: UUID = UUID()
}

struct Section<Model: PSDiffableModelProtocol>: PSDiffableModelProtocol {
let identifier = UUID()
let title: String?
let subtitle: String?
let models: [Model]
}

struct AnyPSDiffableModelProtocol {

private let _identifier: () -> UUID // or implement a function

var idenifier: UUID { return _identifier() }

init<Type: PSDiffableModelProtocol>(_ another: Type) {
_identifier = { another.identifier }
}
}

var sections: [AnyPSDiffableModelProtocol] = []


sections.append(.init(Section(title: "title", subtitle: "subtitle", models: [TodayModel1(), TodayModel1()])))
sections.append(.init(Section(title: "title", subtitle: "subtitle", models: [TodayModel2(), TodayModel2()])))

关于swift - 在数组中使用 PAT 存储通用结构的一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58631811/

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