Swift处理Firebase数据时compactMap报表达式类型歧义错误如何解决
问题原因
- 类型转换错误:报错代码中你将
snapshot.value强制转为String类型,但后续试图把它当做字典数组调用compactMap、取下标["uid"],类型完全不匹配,编译器无法推断表达式类型就抛出了「Type of expression is ambiguous without more context」错误。你可以对比正常运行的代码,合法写法是将value转为[[String: String]]字典数组类型,compactMap遍历每个字典元素的逻辑才成立。 - 数据节点路径不匹配:你监听的节点路径是
\(safetyEmail)/uid,这个节点本身存储的就是单个uid字符串,并非数组结构,不需要调用compactMap遍历。 - 闭包逻辑不完整:你写的
compactMap闭包里只有guard判断逻辑,判断成功后没有返回Ouid实例,不符合高阶函数的语法要求。 - 语法污染:报错行的方括号两侧有多余的
**符号,属于无效语法。
修复方案
根据你的实际需求选择对应修复方式:
场景1:你确实要直接获取单个uid值
不需要用compactMap,直接取值生成Ouid实例即可:
struct Ouid { let uid: String } public var completion: (Ouid) -> Void? var results = [Ouid]() func noteIsHere() { let safetyEmail = DatabaseManager.safeEmail(emailAddress: otherUserEmail) let recentUIDObserve = ref.child("\(safetyEmail)/uid") recentUIDObserve.observeSingleEvent(of: .value, with: { snapshot in guard let uid = snapshot.value as? String else { return } print("this is value: \(uid)") let ouidItem = Ouid(uid: uid) self.results.append(ouidItem) // 按需触发回调 completion?(ouidItem) }) }
场景2:你需要获取某节点下的uid数组
修改监听路径和类型转换逻辑即可:
struct Ouid { let uid: String } public var completion: (Ouid) -> Void? var results = [Ouid]() func noteIsHere() { let safetyEmail = DatabaseManager.safeEmail(emailAddress: otherUserEmail) // 修改为存储uid数组的节点路径 let recentUIDObserve = ref.child("\(safetyEmail)/uidList") recentUIDObserve.observeSingleEvent(of: .value, with: { snapshot in // 类型转为字典数组 guard let value = snapshot.value as? [[String: String]] else { return } print("this is value: \(value)") let results: [Ouid] = value.compactMap({ dictionary in guard let uid = dictionary["uid"] else { return nil } return Ouid(uid: uid) }) self.results.append(contentsOf: results) }) }
内容的提问来源于stack exchange,提问作者personal problem
相关产品推荐
相关产品推荐

