我正在使用 FirebaseDatabase
来存储数据。我有一个简单的模型,可以将 snapshot
数据转换为 post
。问题是,在观察 snapshot
之后,名为 postType
的属性返回 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
是一个枚举
,你不能只将它设置为一个字符串。你所拥有的相当于:post.type = "text"
尝试以这种方式初始化它:
post.type = PostType(rawValue: dictionary["postType"])
您可能需要先解包该值。
if let postType = dictionary["postType"] as? String {
post.type = PostType(rawValue: postType)
}
如何在 playground 中像这样初始化枚举的示例:
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)
Output Optional(__lldb_expr_339.PostType.poll)
您可以在 Documentation 中阅读有关枚举的更多信息.对于这个特定问题;查找标题:“从原始值初始化”
关于swift - 类属性返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50971203/