Swift 4.0中Firestore查询出现Missing Return错误求助
解决Firestore查询中"Missing return in..."错误的方案
这个错误的根源很明确——你的map闭包里存在代码路径没有返回值的情况,我来帮你快速修复:
问题分析
在遍历snapshot.documents的map闭包中,当Post(dictionary: document.data())初始化失败返回nil时,你只打印了错误信息,但没有返回一个Post类型的值。而map要求闭包对每个元素必须返回指定类型(这里是Post)的结果,因此编译器抛出了"Missing return in..."的错误。
最优解决方案:使用compactMap替代map
compactMap会自动忽略闭包返回的nil值,完美适配你的场景——只保留能成功初始化的Post实例,过滤掉无效的文档。修改后的代码如下:
fileprivate func observeQuery() { guard let query = query else { return } stopObserving() listener = query.addSnapshotListener({ [unowned self] (snapshot, error) in guard let snapshot = snapshot else { print("获取快照失败: \(error ?? "未知错误" as! Error)") return } // 用compactMap替代map,自动过滤无法解析的文档 let models = snapshot.documents.compactMap { document -> Post? in if let model = Post(dictionary: document.data()) { return model } else { print("解析文档失败 \(document.documentID): \(error as Any)") return nil // 返回nil,compactMap会自动过滤该元素 } } self.posts = models self.documents = snapshot.documents }) }
你还可以简化成更简洁的写法:
let models = snapshot.documents.compactMap { document in guard let model = Post(dictionary: document.data()) else { print("解析文档失败 \(document.documentID): \(error as Any)") return nil } return model }
备选方案(不推荐):强制在map中返回Post实例
如果你坚持要用map,必须保证所有代码路径都返回Post实例,比如提供一个默认的空Post(需要你的Post类/结构体支持空初始化):
let models = snapshot.documents.map({ (document) -> Post in if let model = Post(dictionary: document.data()) { return model } else { print("解析文档失败 \(document.documentID): \(error as Any)") return Post() // 返回默认的Post实例 } })
⚠️ 这个方案的缺点是无效文档会被转换成空Post,可能干扰后续的UI展示,因此更推荐使用compactMap方案。
内容的提问来源于stack exchange,提问作者David Henry
相关产品推荐
相关产品推荐

