如何在数据模型SwiftUI中将变量设置为多个类型

fcwjkofz  于 2023-04-19  发布在  Swift
关注(0)|答案(1)|浏览(113)

我的SwiftUI应用程序从API端点获取数据。
数据是一个Review,模型如下所示:

struct Review: Identifiable, Decodable {
    var id: Int
    var reviewable_type: String
    var score: Int?
    var reviewable: <THIS CAN BE A MOVIE, A SHOW OR AN EPISODE>
    var user: User
    var created_at: String?
    var created: String?
    var text: String?
}

正如你所看到的,“reviewable”变量可以有多种类型。我如何实现这一点?我有不同的数据模型电影,显示和插曲。注意:reviewable_type保存了reviewable变量中的类型的值。我不知道这是否有帮助?
我尝试了协议和扩展,但似乎无法让它工作

11dmarpk

11dmarpk1#

你可以做的是将structReview转换成一个关联类型的协议,也就是另一个协议Reviewable

protocol Reviewable: Decodable {}

该协议必须至少符合Decodable协议,但也可以包含所有内容之间的公共属性,例如ID。
结构体Review如下转换:

protocol Review: Identifiable, Decodable {
    associatedtype Content: Reviewable
    
    var id: Int { get }
    var score: Int? { get }
    var reviewable: Content { get }
    var created_at: String? { get }
    var created: String? { get }
    var text: String? { get }
}

然后,您将为每种类型的可查看内容创建一个结构体:

struct Movie: Reviewable {}

struct Show: Reviewable {}

struct Episode: Reviewable {}

每个Review Type对应一个struct。

struct MovieReview: Review {
    var id: Int
    var score: Int?
    var reviewable: Movie
    var created_at: String?
    var created: String?
    var text: String?
}

struct ShowReview: Review {
    var id: Int
    var score: Int?
    var reviewable: Show
    var created_at: String?
    var created: String?
    var text: String?
}

struct EpisodeReview: Review {
    var id: Int
    var score: Int?
    var reviewable: Episode
    var created_at: String?
    var created: String?
    var text: String?
}

然后它们都可以在类型为any Review的数据结构中使用。这里有一个简单的例子:

let test: [any Review] = [
                            ShowReview(id: 0, reviewable: Show()),
                            MovieReview(id: 1, reviewable: Movie()),
                            EpisodeReview(id: 2, reviewable: Episode())
                         ]

相关问题