WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: How to remove optional in my network service

Forums > Swift

Hi, I want to use the response data in my service, but for example when I want to access the account variable, I don't want to have to perform an unwrap like this "response.data?.account ?? Account(balance: nil").

This is my code:

class ServiceManager: Service {
    let query = Bundle.main.queryAccountValue

    func getAccount() -> Observable<Result<Account, AccountError>> {
        let accounts = BehaviorRelay<Account>(value: Account(balance: nil))

        let body = ["query": query]
        return response(body: body)
            .flatMap { response -> Observable<Result<Account, AccountError>> in

                guard response.data != nil else {
                    let error = response.errors?.timeDeposit?.first ?? AccountError(code: 10, message: "error")

                        return .just(.failure(error))
                }
                let success = response.data?.account ?? Account(balance: nil)
                accounts.accept(success)
                return .just(.success(success))

                // here i try use if let 
//                if let accountSuccess = response.data?.account {
//                    return .just(.success(accountSuccess))
//                }
            }
    }
}

I know I could use guard let or if let, but when I try to use it I get an error "Missing return in a closure expected to return 'Observable<Result<Account, AccountError>>'" I don't know how I can solve it.

   

So something like this doesn't work?

guard let data = response.data else {
    let error = response.errors?.timeDeposit?.first ?? AccountError(code: 10, message: "error")

    return .just(.failure(error))
}
let success = data.account
accounts.accept(success)
return .just(.success(success))

The reason why this:

if let accountSuccess = response.data?.account {
    return .just(.success(accountSuccess))
}

didn't work is because you aren't returning something if the if let fails. You have to return a value for every path through your code. Or end with a fatalError. One of the two.

1      

Thanks very much!

   

Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.