The return value for the function that throws

I have a pretty simple question, but I could only find a similar answer in the C ++ thread. The compiler complains about the function getUserFromServer

, claiming that it needs a value return

even though it might get an exception. Obviously WHY it is asking for a return value, but I'm not sure how to handle the situation correctly.

One way is to create some kind of dummy user

and return it, but that doesn't seem good. Another way is to return the return type Optional

, but that just shifts the responsibility for nil-check to another level, which is probably not a good idea. Any help would help.

Here's a setup to simulate the behavior I expect in real code.

enum TestError: Error {
    case JustError
}

class User {}
class ServerClient {
    func getUser(really: Bool) throws -> User {
        var uza: User?
        if really {
            uza = User()
        }
        guard let user = uza else {
            throw TestError.JustError
        }
        return user
    }
}

func getUserFromServer() -> User {

    let client = ServerClient()
    let user: User

    do {
        user = try client.getUser(really: true)
        return user
    } catch TestError.JustError {
        print("just an error occured")
    } catch {
        print("something terrible happened")
    }
} //Error: missing return in a function

      

+3


source to share


1 answer


So, imagine I am the caller and I am writing this line of code:

let user = getUserFromServer()
print(user)

      

This is not true. Fine. What would you like? What should it be user

? What should print? (There is no right answer here, the question is, what do you want it to be?)



If you want it to user

be zero then getUserFromServer

should return User?

. If you want to user

be some default user, you need a way to create it. If you want the caller not to print at all (and instead handle some error) then you getUserFromServer()

should throw. If you want it to crash you need to add fatalError

inside getUserFromServer

. They are all valid, but he has to do something, and what it is is up to you.

That said, if the question is just advice on what it should be looking at this code, you should probably make it optional by default, unless you need some other behavior. This would be "normal" here, since you have already "handled" the error.

+4


source







All Articles