swift - 类属性返回 nil
问题描述
我正在使用FirebaseDatabase
存储数据。我有一个简单的模型,可以将snapshot
数据转换为post
. 问题是,在观察 后snapshot
,名为postType
return的属性nil
我不知道为什么。
class Post {
var id : String?
var title : String?
var content : String?
var source : String?
var userUid : String?
var type : PostType?
}
extension Post {
static func transformDataToImagePost (dictionary: [String : Any], key: String) -> Post {
let post = Post()
post.id = key
post.userUid = dictionary["userUid"] as? String
post.title = dictionary["title"] as? String
post.content = dictionary["content"] as? String
post.source = dictionary["source"] as? String
post.type = dictionary["postType"] as? PostType
return post
}
enum PostType: String {
case image = "image"
case gif = "gif"
case video = "video"
case text = "text"
case link = "link"
case audio = "audio"
case poll = "poll"
case chat = "chat"
case quote = "quote"
}
func observePost(withId id: String, completion: @escaping (Post) -> Void) {
REF_POSTS.child(id).observeSingleEvent(of: .value, with: {
snapshot in
if let dictionary = snapshot.value as? [String : Any] {
print(snapshot.value) // <- ["key":value, "postType": text, "key": value]
print(dictionary["postType"]) // <- returns text
let post = Post.transformDataToImagePost(dictionary: dictionary, key: snapshot.key)
print(post.type) // <- returns nil
completion(post)
}
})
}
我就是想不通为什么post.type
退货nil
解决方案
Post.type
是一个enum
,你不能只将它设置为一个字符串。你所拥有的相当于:post.type = "text"
尝试以这种方式初始化它:
post.type = PostType(rawValue: dictionary["postType"])
您可能需要先解开该值。
if let postType = dictionary["postType"] as? String {
post.type = PostType(rawValue: postType)
}
如何在操场上像这样初始化枚举的示例:
enum PostType: String {
case image = "image"
case gif = "gif"
case video = "video"
case text = "text"
case link = "link"
case audio = "audio"
case poll = "poll"
case chat = "chat"
case quote = "quote"
}
let postType = PostType(rawValue: "poll")
print(postType)
输出可选(__lldb_expr_339.PostType.poll)
您可以在文档中阅读有关枚举的更多信息。对于这个特定的问题;查找标题:“从原始值初始化”
推荐阅读
- http - Kubernetes pod 中的 Curl 失败
- git - 在超级仓库中的提交之间递归列出子模块的提交哈希
- google-apps-script - 例外:对 https://docs.google.com 的请求失败,返回代码 401。截断的服务器响应:Google 应用脚本
- firebase-authentication - Firebase Auth SMS 不包含 11 个字符的哈希
- python - ValueError:分类指标无法处理连续目标和多类目标的混合 (XGBoost)
- java - 在 Yarn 上运行 spark 作业时,HDFS Excel 行数减少
- reactjs - react js路由器中的三层路径
- php - 在 SQL 中,如何选择不重复的值?
- git - Git 包超出限制
- reactjs - Redux-thunk 和 Typescript,转换 Action Creator 时出错