无法将“查询”类型的值转换为预期的条件类型“布尔”
Posted
技术标签:
【中文标题】无法将“查询”类型的值转换为预期的条件类型“布尔”【英文标题】:Cannot convert value of type 'Query' to expected condition type 'Bool' 【发布时间】:2021-06-29 20:40:08 【问题描述】:在我的应用程序中,我正在尝试创建一个功能,如果在文档的数组“likedBy”中找到用户 UID,它将变量“isLiked”设置为 true。我有一个名为“checkForLikes”的函数,它链接到我的视图表。
所以,我的项目目标是如果在文档的数组中找到登录的用户 UID(“uid”),则将“isLiked”设置为 true。
但是,在函数中,我收到错误“无法将 'Query' 类型的值转换为预期的条件类型 'Bool'”
PostViewModel.swift
func checkForLikes(id: String)
var doc = ref.collection("Posts")
if doc.whereField("likedBy", arrayContains: uid) /// error is here
print("Found") /// temporary, eventually to be replaced with setting isLiked = true
PostRow.swift
@State private var isLiked = false
HStack
Button(action: if isLiked == false
postData.addLike(id: post.id)
isLiked = true
else
postData.unLike(id: post.id)
isLiked = false
, label:
Image(systemName: isLiked ? "heart.fill" : "heart")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 20, height: 20)
.foregroundColor(isLiked ? .red : .gray)
).onAppear(perform: isLiked = postData.checkForLikes(id: post.id))
Text("\(post.likes)")
.font(.subheadline)
.foregroundColor(.gray)
.fontWeight(.light)
我相信我所拥有的一切都在正确的轨道上,但我正面临着这个错误。如果我走错了路,请告诉我,因为这是我第一次做这样的事情。
【问题讨论】:
【参考方案1】:如您所见,whereField
返回一个Query
。为了对该查询执行某些操作,您需要在其上调用类似 getDocuments
的内容以获得结果:
Firestore.firestore().collection("Posts").whereField("likedBy", arrayContains: uid).getDocuments snapshot, error in
if error != nil
//handle error
return
if snapshot?.documents.count != 0
//it has likes
【讨论】:
【参考方案2】:在我朋友的帮助下,我已经弄清楚了。
*PostViewModel.swift
@State private var isLiked: Bool = false
@State private var isDisabled: Bool = true
func checkForLikes(id: String, then completion: @escaping (Bool?) -> ())
let collection = ref.collection("Posts")
let doc = collection.document(id)
doc.getDocument docSnapshot, err in
if let err = err
print(err)
completion(nil)
return
guard let docSnapshot = docSnapshot,
let likedBy = docSnapshot.data()?["likedBy"] as? [String] else
print("No query snapshot")
completion(nil)
return
completion(likedBy.contains(self.uid))
PostView.swift
HStack
Button
if isLiked == false
postData.addLike(id: post.id)
isLiked = true
else
postData.unLike(id: post.id)
isLiked = false
label:
Image(systemName: isLiked ? "heart.fill" : "heart")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 20, height: 20)
.foregroundColor(isLiked ? .red : .gray)
.disabled(isDisabled)
.opacity(isDisabled ? 0.3 : 1)
.onAppear
postData.checkForLikes(id: post.id) isLiked in
if let isLiked = isLiked
withAnimation(.easeInOut(duration: 0.2))
isDisabled = false
self.isLiked = isLiked
【讨论】:
以上是关于无法将“查询”类型的值转换为预期的条件类型“布尔”的主要内容,如果未能解决你的问题,请参考以下文章