How to check if a URL is valid in Swift?

2 views

Swift validation of a URL string can be achieved using the URL constructor. Attempting to create a new URL object with an invalidly formatted string will result in an error. If the URL object is successfully created, then it confirms the given string represents a valid URL structure.

Comments 0 like

How to check if a URL is valid in Swift?

Swift validation of a URL string can be achieved using the URL constructor. Attempting to create a new URL object with an invalidly formatted string will result in an error. If the URL object is successfully created, then it confirms the given string represents a valid URL structure.

Here’s an example of how to check if a URL is valid in Swift:

let urlString = "https://www.apple.com"

// Check if the URL is valid
if let url = URL(string: urlString) {
    // The URL is valid
    print("The URL is valid: (url)")
} else {
    // The URL is invalid
    print("The URL is invalid: (urlString)")
}

In this example, we first create a URL string. Then, we use the URL(string:) constructor to attempt to create a URL object from the string. If the constructor succeeds, it means the URL string is valid and we print the URL object. If the constructor fails, it means the URL string is invalid and we print an error message.

Here are some additional examples of valid and invalid URL strings:

Valid URL strings:

  • https://www.apple.com
  • http://www.apple.com
  • www.apple.com
  • apple.com

Invalid URL strings:

  • https://www.apple
  • http://www.apple
  • www.apple
  • apple

By using the URL(string:) constructor, you can easily check if a URL string is valid in Swift. This can be useful for validating user input, or for ensuring that your code is working with valid URLs.