Skip to content

Instantly share code, notes, and snippets.

@sigidhanafi
Last active April 19, 2022 15:06
Show Gist options
  • Save sigidhanafi/bfdeecae39855444e229868e60814475 to your computer and use it in GitHub Desktop.
Save sigidhanafi/bfdeecae39855444e229868e60814475 to your computer and use it in GitHub Desktop.
import UIKit
// Step 2 create enum for custom error
enum CustomError: Error {
case invalidUrl
case emptyUrl
case other
}
// Step 1. function with throws keyword
func validateUrl(urlString: String) throws -> Bool {
guard !urlString.isEmpty else {
throw CustomError.emptyUrl
}
guard URL(string: urlString) != nil else {
throw CustomError.invalidUrl
}
return true
}
// Step 3 call the function with do try catch
let urlString = ""
do {
let result = try validateUrl(urlString: urlString)
// Step 5 continue the process if it success
print("is url valid? \(result)")
}
catch {
// Step 4 show error to users
print("error \(error)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment