ios - Swift 作用域规则——设置非 nil 值后的 nil 值

标签 ios swift swift2 ios9

我正在编写一个与 Firebase 交互的数据服务。我在闭包内设置 self.realID ,当我在闭包外引用它时,它失败了,因为它展开了一个 nil 值。为什么会这样?

我的文件:

import Foundation
import Firebase

class Database {

    var firebaseRef = Firebase(url:"https://<<UNIQUE>>.firebaseio.com")

    class var sharedInstance: Database {
        struct Data {
            static var instance: Database?
            static var token: dispatch_once_t = 0
        }

        dispatch_once(&Data.token) {
            Data.instance = Database()
        }

        return Data.instance!
    }

    var uid : String!

    var realID : String!

    var validated = false

    func validate(user: String, study: String) -> Bool {

        firebaseRef.authUser(user+"@example.com", password: user,
             withCompletionBlock: { error, authData in
                if error != nil {
                    NSLog(String(error))
                } else {
                    self.uid = authData.uid
                    NSLog(authData.uid)
                }
        })

        let usersRef = Firebase(url: "https://<<UNIQUE>>.firebaseio.com/users")
        usersRef.observeEventType(FEventType.Value, withBlock: { (snapshot) in
            let value = snapshot.value.objectForKey("study") as! String
            self.realID = value
            NSLog(self.realID) // this is a non-nil value
        })

        NSLog("About to encounter nil value and crash")
        if self.realID == study {
            return true
        }
        return false
    }
}

如何防止这种 fatal error 的发生?

最佳答案

您需要添加一个 completionHandler,因为它是异步请求。如果您要设置断点,则在设置 id 之前执行返回。

func validate(user: String, study: String, completionHandler:(Bool) -> Void) {

    let usersRef = Firebase(url: "https://<<UNIQUE>>.firebaseio.com/users")
    usersRef.observeEventType(FEventType.Value, withBlock: { (snapshot) in
        if let value = snapshot.value.objectForKey("study") as? String {
            self.realID = value
            completionHandler(true)
        } else {
            completionHandler(false)
        }
    })

}

更新

validate("Rahul", study: "Study") { (value: Bool) in
    if value {

    } else {

    }
}

关于ios - Swift 作用域规则——设置非 nil 值后的 nil 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36564283/

相关文章:

iphone - 区分文件和文件夹与 iphone 上的文档目录

ios - 使用自定义按钮从 Core Data UITableView 中删除一行

ios - 将 2 个字典分组到 Swift 数组中存在的数组中

ios - 添加到 Stackview subview 的 CAShapeLayers 仅在一个 subview 上呈现

ios - 有没有办法操纵 NSUserDefaults 存储的信息

ios - 同步随机数

ios - 如何将 C 函数返回的 'void *' 转换为 Swift 3 中的 'UnsafeMutableRawPointer'?

ios - 自定义子类中的变量不会保存/不会从核心数据加载

swift - Swift 2.2 中 Alamofire 请求的返回值

ios - 导航项左侧和顶部未显示