kimo26
kimo26

Reputation: 47

I've got a Unexpected non-void return value in void function error?

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    switch section {
    case 0:

redeclaration of a var statement

        one = Database.database().reference()

collecting information from database

        one.child("users").child("profile").observe(.value, with: {(snapshot) in
            let num = snapshot.childrenCount

where the error arises

            return Int(num)
        })
    default:
        return 0
    }

}

Upvotes: 0

Views: 361

Answers (2)

Stany Miles
Stany Miles

Reputation: 212

Doug Stevenson is right!

What you can do instead is after you get your data from server, parse it and save it to a variable and update your collectionView.

var data = [YourModel]()

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return data.count
}

Database.database().reference().child("users").child("profile").observe(.value, with: {(snapshot) in

    let values = snapshot.values as? [String: Any] else { return }

    var tmpArrayOfValues = [YourModel]()

    // here you create YourModel objects
    values.forEach { (item) in
        let newItem = //create your item from values
        tmpArrayOfValues.append(newItem)
    }    

    self.data = tmpArrayOfValues

    // to update UI you have to return to main thread, because firebase func are running on background thread
    DispatchQueue.main.async {
        self.collectionView.reloadData()
    }
}

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317712

This function that you're passing to observe is typed as a function that returns void:

{(snapshot) in
    let num = snapshot.childrenCount
    return Int(num)
})

You can see from the API docs for observe:

Declaration

func observe(_ eventType: DataEventType, with block: @escaping (DataSnapshot) -> Void) -> UInt

The type of the function is (DataSnapshot) -> Void, which means that it can not return a value. But you're returning Int(num) instead.

You won't be able to return the result of a database query from collectionView() because the database observer is asynchronous and returns immediately. It will give you a value some time later, and you have no guarantee how long it will take.

Upvotes: 1

Related Questions