无法在火力基地中将类型"NSNull"的值转换为"NSString"



我正试图从firebase中的数据库中提取文章,但在这个函数的let author部分遇到了SIGABRT错误,怎么了?

func getAllArticles(handler: @escaping (_ articles: [Article])-> ()){
var articleArray = [Article]()
REF_ARTICLES.observeSingleEvent(of: .value) { (articleMessageSnapshot) in
guard let articleMessageSnapshot = articleMessageSnapshot.children.allObjects as? [DataSnapshot] else {return}
for article in articleMessageSnapshot {
let content = article.childSnapshot(forPath: "content").value as! String
let author = article.childSnapshot(forPath: "author").value as! String
let twitterHandle = article.childSnapshot(forPath: "twitterHandle").value as! String
let articleTitle = article.childSnapshot(forPath: "articleTitle").value as! String
let article = Article(content: content, author: author, twitterHandle: twitterHandle, ArticleTitle: articleTitle)
articleArray.append(article)
}
handler(articleArray)
}
}

我对Firebase一无所知,但从你发布的内容来看,我不认为这是你的问题。

此代码article.childSnapshot(forPath: "author").value返回NSNull,这意味着它没有找到与您的条件匹配的值。代码as! String的字面意思是,如果值不是String,就会崩溃。由于NSNull不是String,所以会发生崩溃。

一种解决方案:

let author = article.childSnapshot(forPath: "author").value as? String ?? "No Author"

任何人都可能对所有的台词都这么做。另请阅读Swift选项和强制拆封。

相关内容

最新更新