I am trying to write some code that lets me both validate that a string is in fact a valid web address to reach a remote server && be able to unwrap it safely into a url for usage.
From what gathered from various posts and Apple's source code:
URLComponents is a structure designed to parse URLs based on RFC 3986 and to construct URLs from their constituent parts.
and based on w3 schools:
A URL is a valid URL if at least one of the following conditions holds:
The URL is a valid URI reference [RFC3986]....
Would this code suffice to detect addresses that reach remote servers on the world wide web?
import Foundation
extension String {
/// Returns `nil` if a valid web address cannot be initialized from self
var url: URL? {
guard
let urlComponents = URLComponents(string: self),
let scheme = urlComponents.scheme,
isWebServerUrl(scheme: scheme),
let url = urlComponents.url
else {
return nil
}
return url
}
/// A web address normally starts with http:// or https:// (regular http protocol or secure http protocol).
private func isWebServerUrl(scheme: String) -> Bool {
(scheme == WebSchemes.http.rawValue || scheme == WebSchemes.https.rawValue)
}
}
Can you provide some feedback on this approach and let me know if there are any optimizations that can be made? or if it's incorrect?
Any and all comments are appreciated.