'Swift future publisher error when getting data from firebase
I'm new to swift language, but now I'm developing app with swift and firebase. I'm using realtime database and while making two identical functions for getting data one is working and one is not.
This is the working one:
func getRoom(admin: String) -> AnyPublisher<Room, Error> {
Deferred {
Future { promise in
Database.database().reference().child("rooms/\(admin)")
.getData { [self] error, snapshot in
guard error == nil else {
promise(.failure(error!))
print(error!.localizedDescription)
return;
}
let value = snapshot.value as? [String:[String:Any]]
for (key, room) in value ?? [:] {
if (key == admin){
let admin = room["admin"] as? [String:Any]
let subjects = room["subjects"] as? [String]
let difficulties = room["difficulties"] as? [String]
let users = room["users"] as? [[String:Any]]
let questions = room["questions"] as? [[String:Any]]
let isGameStarted = room["is_game_started"] as? String
let room = Room(admin: dictionaryToUser(userDict: admin!), subjects: subjects!, difficutlies: difficulties!, users: dictionaryToUsersArr(usersArrDict: users!), questions: dictionaryToQuestionArr(questionsArrDict: questions!), is_game_started: isGameStarted!)
promise(.success(room))
}
}
}
}
}
.eraseToAnyPublisher()
}
And this is not working:
func getRoomUsersFromRoom(admin: String) -> AnyPublisher<[RoomUser], Error> {
var roomUsers: [RoomUser] = []
Deferred {
Future { promise in
Database.database().reference()
.child("rooms/\(admin)")
.getData { error, snapshot in
guard error == nil else {
promise(.failure(error!))
print(error!.localizedDescription)
return;
}
let value = snapshot.value as? [String:[String:Any]]
for (key, room) in value ?? [:] {
if (key == admin){
let users = room["users"] as? [[String:Any]]
for i in 0..<users!.count {
roomUsers.append(RoomUser(username: users![i]["username"] as! String, gamePoints: users![i]["room_points"] as! Int))
}
promise(.success(roomUsers))
}
}
promise(.success(roomUsers))
}
}
}
.eraseToAnyPublisher()
}
The errors in the second one are on the line with the Future, telling:
"Generic parameter 'Failure' could not be inferred"
"Generic parameter 'Output' could not be inferred"
It suggests me to put Future<Any, Error> and the error is gone but then I have warning on "eraseToAnyPublisher()", which I think is not good.
What is difference between the functions and any ideas how to solve this?
Thanks in advance
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
