Skip to content

Instantly share code, notes, and snippets.

@yakuter
Last active March 13, 2023 10:03
Show Gist options
  • Save yakuter/b02b0761f25771df214a5e3b3bacef36 to your computer and use it in GitHub Desktop.
Save yakuter/b02b0761f25771df214a5e3b3bacef36 to your computer and use it in GitHub Desktop.
Swift error handling
// 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