UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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.

2      

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.

3      

Thanks very much!

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.