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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.