Last active
March 13, 2023 10:03
-
-
Save yakuter/b02b0761f25771df214a5e3b3bacef36 to your computer and use it in GitHub Desktop.
Swift error handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Method 1 | |
struct User { | |
} | |
enum SecurityError: Error { | |
case emptyEmail | |
case emptyPassword | |
} | |
class SecurityService { | |
static func loginWith(email: String, password: String) throws -> User { | |
if email.isEmpty { | |
throw SecurityError.emptyEmail | |
} | |
if password.isEmpty { | |
throw SecurityError.emptyPassword | |
} | |
return User() | |
} | |
} | |
do { | |
let user = try SecurityService.loginWith1(email: "", password: "") | |
} catch SecurityError.emptyEmail { | |
// email is empty | |
} catch SecurityError.emptyPassword { | |
// password is empty | |
} catch { | |
print("\(error)") | |
} | |
// Method 2 | |
guard let user = try? SecurityService.loginWith(email: "", password: "") else { | |
// error during login, handle and return | |
return | |
} | |
// successful login, do something with `user` | |
// Method 3 | |
If you just want to get User or nil: | |
class SecurityService { | |
static func loginWith(email: String, password: String) -> User? { | |
if !email.isEmpty && !password.isEmpty { | |
return User() | |
} else { | |
return nil | |
} | |
} | |
} | |
if let user = SecurityService.loginWith(email: "", password: "") { | |
// do something with user | |
} else { | |
// error | |
} | |
// or | |
guard let user = SecurityService.loginWith(email: "", password: "") else { | |
// error | |
return | |
} | |
// do something with user |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment