OStack程序员社区-中国程序员成长平台

标题: ios - 访问闭包之外的数据//iOS Swift [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:13
标题: ios - 访问闭包之外的数据//iOS Swift

如何在闭包之外访问“用户”?

    let currentUser = FIRDatabase.database().reference(withPath: "users").child((FIRAuth.auth()!.currentUser?.uid)!)
        currentUser.observeSingleEvent(of: FIRDataEventType.value, with: { snapshot in
        let value = snapshot.value as? NSDictionary
        let name = value?["name"] as? String
        let age = value?["age"] as? String
        let user = UserStruct.init(name: name, age: age)
    })

Firebase 中的一切都正确无误,并且数据存在且不为零。但我需要像这样在闭包之外引用“用户”:

print(user.name)
print(user.age)



Best Answer-推荐答案


在闭包之外声明 user 变量,然后使用 self 修饰符访问它。

    var user: UserStruct
    let currentUser = FIRDatabase.database().reference(withPath: "users").child((FIRAuth.auth()!.currentUser?.uid)!)
        currentUser.observeSingleEvent(of: FIRDataEventType.value, with: { snapshot in
        let value = snapshot.value as? NSDictionary
        let name = value?["name"] as? String
        let age = value?["age"] as? String
        self.user = UserStruct.init(name: name, age: age)
    })

关于ios - 访问闭包之外的数据//iOS Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40917864/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4