函数不允许返回值

时间:2019-12-17 13:19:58

标签: swift firebase google-cloud-platform google-cloud-firestore swiftui

如果用户能够从Firestore删除alert,我将尝试建立一个post对话框。这就是我要尝试的方式,我知道这是错误的,因此我需要一些支持来改善自己的思想。

func validateDelete()->Bool{
    let uid = Auth.auth().currentUser!.uid
    db.collection("posts").whereField("UID", isEqualTo: uid).getDocuments() { (querySnapshot, err) in
      if let err = err {
        print("Error getting documents: \(err)")
      } else {
        for document in querySnapshot!.documents {


    return true;
        }
      }
    }
    return false
}

因为我希望它像这样使用它:

enum ActiveAlert {
    case delete, denied
}

struct ToggleView: View {
    @State private var showAlert = false
    @State private var activeAlert: ActiveAlert = .delete

    var body: some View {

        Button(action: {
            if validateDelete {
                self.activeAlert = .delete
            } else {
                self.activeAlert = .denied
            }
            self.showAlert = true
        }) {
            Text("Show random alert")
        }
        .alert(isPresented: $showAlert) {
            switch activeAlert {
            case .delete:
                Alert(title: Text("Are you sure you want to delete this?"), message: Text("There is no undo"), primaryButton: .destructive(Text("Delete")) {
 document.reference.delete()
                    print("Deleting...")
            }, secondaryButton: .cancel())
            case .denied:
                return Alert(title: Text("Important message"), message: Text("you don't have permission to delete this"))
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您不能像尝试这样做那样从闭包内部返回,而应使用从函数内部调用的完成处理程序。

func validateDelete(completion: @escaping (Bool)-> Void) {

然后而不是return true //or false而是completion(true)

当调用该函数时,您可以像这样使用它

validateDelete { flag in
    if flag {
        self.activeAlert = .delete
    } else {
        self.activeAlert = .denied
    }
}

我不使用firebase,但我想整个功能看起来像这样

func validateDelete(completion: @escaping (Bool)-> Void) {
    let uid = Auth.auth().currentUser!.uid
    db.collection("posts").whereField("UID", isEqualTo: uid).getDocuments() { (querySnapshot, err) in
    if let err = err {
        print("Error getting documents: \(err)")
        completion(false)
    } else {
        let exists = querySnapshot!.documents.count > 0
        completion(exists)
    }
}