我正在开发一个从Firebase获取数据的应用。我要向你展示的代码工作正常,但即使作为一个新手,我知道实施应该更好。我真的无法弄清楚如何重构这个。
这是TLDR:
我创建了一个数据模型,用于设计BlogPosts。我为此使用了Struct,在初始版本中,我的所有属性都是String类型。
但是,除了标题和摘要的字符串,我的帖子还包含图像的URL和日期(发布日期)。
我希望能够从我的BlogPost对象返回更具体的对象,例如已经创建的URL或Date对象。
就像我说的,我知道我的实现很糟糕,我想学习一种更好的类型转换方式,以便我可以实现上述行为。
以下是我的BlogPost数据模型的实现:
import Foundation
import FirebaseDatabase
struct BlogPost {
let key: String
let title: String
let body: String
let summary: String
let author: String?
let liveSince: Date
let featuredImageLink: URL?
let itemReference:DatabaseReference?
init(snapshot: DataSnapshot) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-mm-dd"
key = snapshot.key
itemReference = snapshot.ref
if let snapshotDictionary = snapshot.value as? NSDictionary, let postTitle = snapshotDictionary["Title"] as? String {
title = postTitle
} else {
title = "Cannot display Title for this item :("
}
if let snapshotDictionary = snapshot.value as? NSDictionary, let postBody = snapshotDictionary["Body"] as? String {
body = postBody
} else {
body = "Cannot display Body for this item :("
}
if let snapshotDictionary = snapshot.value as? NSDictionary, let postSummary = snapshotDictionary["Summary"] as? String {
summary = postSummary
} else {
summary = "Due to some weird error, the Summary for this item cannot be displayed. Insert more coffee and Pizza in developer"
}
if let snapshotDictionary = snapshot.value as? NSDictionary, let postAuthor = snapshotDictionary["Author"] as? String {
author = postAuthor
} else {
author = "Nobody wrote this :("
}
if let snapshotDictionary = snapshot.value as? NSDictionary, let postImageLink = snapshotDictionary["FeaturedImage"] as? String {
featuredImageLink = URL(string: postImageLink)!
} else {
featuredImageLink = URL(string:"https://someimagelink")!
}
if let snapshotDictionary = snapshot.value as? NSDictionary, let liveDate = snapshotDictionary["LiveSince"] as? String {
if let live = dateFormatter.date(from: liveDate) {
liveSince = live
} else {
liveSince = dateFormatter.date(from: "1990-06-26")!
}
} else {
liveSince = dateFormatter.date(from: "1990-06-26")!
}
}
}
任何建设性的反馈都非常受欢迎,因为我真的想要了解如何正确地做到这一点,或者首先是否有意义这样做!
非常感谢你提前回复!
答案 0 :(得分:1)
我有一些建议。看起来你继续使用条件绑定来展开snapshsot.value,同时将其作为NSDictionary进行转换。由于展开此值是解开其他值的先决条件,为什么不使用guard语句来解包呢?在guard语句中,您可以默认初始化结构中的所有属性。或者,如果您不坚持默认初始化属性,则可以使用可用的初始化程序,并在guard语句中返回nil。
guard let snapshotDictionary = snapshot.value as? NSDictionary else {
title = "Cannot display Title for this item :("
body = "Cannot display Body for this item :("
summary = "Due to some weird error, the Summary for this item cannot be
displayed. Insert more coffee and Pizza in developer"
...
...
}