2017-03-28 9 views
0

変数numはobserveSingleEventの内部で変更されますが、空の値に変更された直後に変更されます。どのようにnumの値を変更するのですか?observeSingleEventで変数の値が変更されない

var num = Int() 
    FIRDatabase.database().reference().child("menus/Day1").observeSingleEvent(of: .value, with: {(snap) in 

    print(snap) 

    if let snapDict = snap.value as? [String:AnyObject]{ 

     self.num = snapDict["date"] as! Int 
     print(num) 
     //returns the number I want 

    } 
    }) 

    print(num) 
    //Returns an empty value 

    if num == 5 { 
     print("number is 5") 
    else { 
     print("number is not 5") 
     //goes to this 
    } 
+0

また、データに変更を加えるには、 'observeSingleEvent'ではなく' observeEventOfType'を使用してください。 –

+0

@FrankvanPuffelenありがとうございました! – user7780338

+1

2番目の 'print(num)'が空の値であるのは、Firebaseが非同期であるためです。最後の印刷は、完了ハンドラ内の印刷の前に実行されます。 – dstepan

答えて

1

あなたはFirebaseから戻って来ている値を使用して行う必要があり、任意の作業は完了ハンドラ(メソッド呼び出しのwith一部)内で行われなければなりません。 Firebaseから取得したnumの値を使用/操作するには、完了ハンドラ内で使用する必要があります。

var num = Int() 

FIRDatabase.database().reference().child("menus/Day1").observeSingleEvent(of: .value, with: {(snap) in 

    print(snap) 

    if let snapDict = snap.value as? [String:AnyObject]{ 

     self.num = snapDict["date"] as! Int 

     if self.num == 5 { 
      print("number is 5") 
     else { 
      print("number is not 5") 
     } 
    } 
}) 
関連する問題