ios - Swift async method and return / completion block -
i'm trying create async method in project takes input parameters. if parameters correct stuff , call completion block.
however, if input parameters not correct won't stuff (and completion block won't run , i'd have call myself).
anyway, i'm wondering best approach this...
i'm thinking have method return status
enum includes wrong input , have completion block.
the problem there error completion block. maybe should different error type?
something this... (using login example).
enum loginrequeststatus { case missingemail case missingpassword case requestinglogin }
and error completion might be...
enum loginerror: error { case nouserfound case invalidpassword case success }
then function might this...
func login(withemail email: string, password: string, completion: (loginerror?) -> ()) -> loginstatus { if email.isempty() { return loginstatus.missingemail } if password.isempty() { return loginstatus.missingpassword } //make async request here or something... //... if error... completion(loginerror.invalidpassword) return loginstatus.requestinglogin }
does make sense? swifty (i hate word portrays mean)? there different way approach altogether?
thanks
from point of view possible use throws
simplify interaction method. write small example. implementation quite easy not miss error because of exceptions
. , clear response status show if request successful.
throws errors:
enum loginerror: errortype { case missingemail case missingpassword }
response status:
enum loginrequeststatus { case nouserfound case invalidpassword case success }
function implementation:
func login(withemail email: string, password: string) throws -> loginrequeststatus { guard email.characters.count > 0 else{ throw loginerror.missingemail } guard password.characters.count > 0 else{ throw loginerror.missingpassword } // request return loginrequeststatus.success }
Comments
Post a Comment