访问Closure // iOS Swift之外的数据

时间:2016-12-01 18:27:45

标签: 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中的一切都是正确的,数据在那里并且不是零。但我需要引用" user"在闭幕之外如此:

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

1 个答案:

答案 0 :(得分:0)

在闭包之外声明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)
    })