首页 > 解决方案 > Swift中的数据模型,具有多个基于彼此的变量

问题描述

我目前陷入需要创建一个数据模型的情况,该模型将在 UITableView 中用于添加帖子和检索它们(阅读:在提要中显示它们)。请允许我解释一下:

我想为帖子创建一个标准数据模型,其中包含标题、正文和标签。我为此使用了一个结构。

struct Post {
    var Title: String
    var Body: String
    var Tags: [String]
}

这很好用。我可以重新使用它来同时创建多个帖子,UITableView这正是我想要的。但是,当我想改进我的系统时,问题就出现了。我想允许用户添加附件,无论它们是图像还是视频(让我们将其保留在这两个示例中,并省略文本文档、pdf 等)。我UITableView的设置方式是每个部分都是一个帖子,每一行都是该帖子的一个项目。标题UITextField在节标题中定义,标签在节的页脚中定义。身体是一排。我现在想允许用户添加一行来添加他们想要的任何内容:纯文本(“正文”行),还有图像或视频。我将创建三个按钮:添加文本、添加图像和添加视频。

我怎样才能改进我的数据模型,以便它可以保存所有这些信息?例如,我应该为所有类型(图像和视频)添加一个变量“附件”,还是应该创建单独的可选变量,如下所示:

struct Post {
    var postTitle: String
    var postBody: String
    var postTags: [String]
    var postImages: [AttachmentImage]
    var postVideos: [AttachmentVideo]
}

struct AttachmentImage {
    var imageTitle: String
    var imageReference: String
    var imageSize: Int
}

struct AttachmentVideo {
    var videoTitle: String
    var videoReference: String
    var videoSize: Int
    var videoThumbnail: String
}

这似乎是可能的,但我想以某种方式实现我可以根据另一个变量更改变量。理想情况下,我会有类似的东西:

enum PostTypes {
    case Text, Image, Video
}

struct Post {
    var postTitle: String
    var postBody: String
    var postTags: [String]
    var postType: PostTypes
}

然后,如果类型是 Text,我想保持原样,但如果类型是 Image,我想添加 imageTitle、imageReference 和 imageSize,对于 Video 也是如此。有没有办法实现这一点,还是我应该选择选项?

标签: iosswiftdata-modeling

解决方案


First as first:如果您有模型命名Post,则不必将其属性命名为postTitle,postBody等......title或者body就足够了。


您可以为您的结构定义协议,然后您可以为您的Post结构添加通用约束

protocol Attachment {
    var title: String { get set }
    var reference: String { get set }
    var size: Int { get set }
}

struct Post<T: Attachment> {
    var title: String
    var body: String
    var tags: [String]
    var attachments: [T]
}

struct AttachmentImage: Attachment {
    var title: String
    var reference: String
    var size: Int
}

struct AttachmentVideo: Attachment {
    var title: String
    var reference: String
    var size: Int
    var thumbnail: String
}

示例用法:

let post = Post(title: "", body: "", tags: [], attachments: [AttachmentImage(title: "", reference: "", size: 1)])
post.attachments /* type: [AttachmentImage] */

let post = Post(title: "", body: "", tags: [], attachments: [AttachmentVideo(title: "", reference: "", size: 1, thumbnail: "")])
post.attachments /* type: [AttachmentVideo] */

推荐阅读