从闭包传递值获取到其他类的正确方法是什么? [英] What is the right way to pass the value get from closure to other class?

查看:36
本文介绍了从闭包传递值获取到其他类的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从闭包中获取变量 guestname 的值,并且 guestname 被定义为全局virable,然后将此值传递给使用它的其他类.但是问题是,当我在闭包外面打印 guestname 时,它是空的,但是在里面我看到了实际值.因此,当我将 guestname 传递给其他类时,它传递nil会引起问题.将值分配给 guestname 并从封闭中获取该值的正确方法是什么?谢谢

I want to get value for variable guestname from closure and guestname is defined as global virable then pass this value to other class that use it. But the problem is that when i print out the guestname outside the closure it's empty but inside i see the actual value. So when i passed guestname to other class it pass nil caused problem. What is correct way to assign the value to guestname and get this value out of closure? Thanks

queryUserID?.getFirstObjectInBackground(block: { (object, error) in
                if error == nil {
                guestname = object!.value(forKey: "username") as! String

                }
            })

推荐答案

我认为您必须像所有完成块一样,从闭包本身传递数据

I think you must pass data from closure itself like all completion blocks do

queryUserID?.getFirstObjectInBackground() { [weak CLASS] (object, error) in
    if let unwrappedObject = object as? String,
        error == nil {
            guestname = unwrappedObject.value(forKey: "username")
            CLASS?.passData(guestname)
    }
}

这篇关于从闭包传递值获取到其他类的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆