菜鸟教程小白 发表于 2022-12-11 18:13:29

ios - 访问闭包之外的数据//iOS Swift


                                            <p><p>如何在闭包之外访问“用户”?</p>

<pre><code>    let currentUser = FIRDatabase.database().reference(withPath: &#34;users&#34;).child((FIRAuth.auth()!.currentUser?.uid)!)
      currentUser.observeSingleEvent(of: FIRDataEventType.value, with: { snapshot in
      let value = snapshot.value as? NSDictionary
      let name = value?[&#34;name&#34;] as? String
      let age = value?[&#34;age&#34;] as? String
      let user = UserStruct.init(name: name, age: age)
    })
</code></pre>

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

<pre><code>print(user.name)
print(user.age)
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>在闭包之外声明 <code>user</code> 变量,然后使用 <code>self</code> 修饰符访问它。</p>

<pre><code>    var user: UserStruct
    let currentUser = FIRDatabase.database().reference(withPath: &#34;users&#34;).child((FIRAuth.auth()!.currentUser?.uid)!)
      currentUser.observeSingleEvent(of: FIRDataEventType.value, with: { snapshot in
      let value = snapshot.value as? NSDictionary
      let name = value?[&#34;name&#34;] as? String
      let age = value?[&#34;age&#34;] as? String
      self.user = UserStruct.init(name: name, age: age)
    })
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 访问闭包之外的数据//iOS Swift,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/40917864/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/40917864/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 访问闭包之外的数据//iOS Swift