Search code examples
swiftfirebaseerror-handlingthrow

How can I convert this function to a throwing function?


I'm trying to develop my skills in Swift and would gladly appreciate any help on how to user "throws" in the function below.

I think it's a convenient way to user throw so that I can present an alert controller to the user telling them what's wrong:

    enum networkError: Error {
    case invalidURL
    case invalidUserinfo
    case invalidData
    case standard
    case nilProperty
}

func createUsers(completion: @escaping(User) -> ()) {

    REF_USER.observe(.childAdded) { (snapshot) in
        let uid = snapshot.key
        guard
            let dict = snapshot.value as? Dictionary<String,String>,
            let fullname = dict["fullname"],
            let profileImageUrl = dict["profileImageUrl"]
        else { return }

       guard let url = URL(string: profileImageUrl) else { return }

       URLSession.shared.dataTask(with: url) { (d, r, e) in
        if e != nil {
            print("DEBUG: Error fetching users profile image", e)
            return
        }
        guard let data = d else { return }
        guard let image = UIImage(data: data) else { return }

        let user = User(uid: uid, fullname: fullname, profileImage: image, isFollowed: false)
        completion(user)
       }.resume()
    }

}


Solution

  • Instead of passing a User back into your completion handler, you pass a Result. You can use it almost without any change, because Result has a really cool initializer:

    • If you return a User, the caller gets a .success with that User wrapped up inside.

    • If you throw, the caller gets a .failure with the thrown Error wrapped up inside.

    And, on the far side, the caller can send the Result the get message to unwrap the Result with similar coolness.