输入'Any?'没有下标成员(使用Firebase)

时间:2017-01-24 18:36:38

标签: ios swift3

每次我运行这行代码都不起作用,任何能够帮助我做我能做的事的人都会改变它吗?谢谢你的帮助。 :)

以下是我一直遇到的错误

  

输入任何?没有下标成员

var ref:FIRDatabaseReference?
var refHandle: UInt!


var postData = [String]()

override func viewDidLoad() {

    super.viewDidLoad()



    ref = FIRDatabase.database().reference()
    refHandle = ref?.observe(FIRDataEventType.value, with:
    { (snapshot) in

        let dataDict = snapshot.value as! [String: AnyObject]

        print(dataDict)


    })

    let username: String = (FIRAuth.auth()?.currentUser?.uid)!

    ref?.child("Users").child(username).observeSingleEvent(of: .value, with:
    { (snapshot) in
        let username = snapshot.value!["Username"] as! String

        self.usernameField.text = username


    })

}

1 个答案:

答案 0 :(得分:2)

两个问题。

<强> 1。自选

这是Swift使变量处于两种状态之一的方式,即具有值或nil。变量只能处于其中一种状态。您可以通过在其前面添加问号来使变量成为可选项。

<强> 2。任何

通过将变量声明为Any类型,这意味着您在声明期间没有明确说明其类型。 Firebase使其所有返回值都为Any类型,以便我们开发人员可以选择摆弄数据,因为我们因此请求更少的限制。

snapshot.value的类型为Any,但Firebase始终返回JSON树,而JSON树可以表示为Dictionaries。那我们该怎么办?

  1. 由于snapshot.value是可选的,我们应首先检查其nil
  2. 如果不是nil,请将其转换为字典,然后开始访问其中的相应元素。
  3. 下面的代码为您完成了工作,我添加了评论来解释发生了什么。

    ref?.child("Users").child(username).observeSingleEvent(of: .value, with:
    { (snapshot) in
    
        // This does two things.
        // It first checks to see if snapshot.value is nil. If it is nil, then it goes inside the else statement then prints out the statement and stops execution.
        // If it isn't nil though, it converts it into a dictionary that maps a String as its key and the value of type AnyObject then stores this dictionary into the variable firebaseResponse.
    
        // I used [String:Any] because this will handle all types of data types. So your data can be Int, String, Double and even Arrays.
        guard let firebaseResponse = snapshot.value as? [String:Any] else
        {
            print("Snapshot is nil hence no data returned")
            return
        }
    
        // At this point we just convert the respective element back to its proper data type i.e from AnyObject to say String or Int etc
    
        let userName = firebaseResponse["Username"] as! String
    
        self.usernameField.text = username     
    })