Skip to content

Instantly share code, notes, and snippets.

@sturdysturge
Created December 19, 2020 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sturdysturge/5c364e2513e372f9cb12258757d65136 to your computer and use it in GitHub Desktop.
Save sturdysturge/5c364e2513e372f9cb12258757d65136 to your computer and use it in GitHub Desktop.
CreateURL
import Foundation
extension URL {
enum Scheme: String { case http, https }
enum Subdomain: String { case maps, translate, noSubdomain = "" }
enum DomainName: String { case apple, google }
enum DomainExtension: String { case com, couk = "co.uk" }
enum PathComponent: String { case accessibility }
/// Create a URL using cases from the enums above
/// - Parameters:
/// - scheme: Could be https or a custom URL scheme
/// - subdomain: An optional part of the host name that is separated from the domain name automatically (so no '.' should be given in the parameter)
/// - domainName: The main part of the host name that describes the website (without the '.' or extension)
/// - domainExtension: The extension after the host name (without the '.')
/// - pathComponents: The directory path that will be separated by slashes automatically (so no slashes should be given in the parameter)
init?(scheme: Scheme, subdomain: Subdomain? = .noSubdomain, domainName: DomainName, domainExtension: DomainExtension, pathComponents: [PathComponent]? = []) {
//The URL will be constructed from components
var urlComponents = URLComponents()
//Add scheme
urlComponents.scheme = scheme.rawValue
//Add hostname
var hostname = [String]()
if let subdomain = subdomain, !subdomain.rawValue.isEmpty {
hostname = [subdomain.rawValue, domainName.rawValue, domainExtension.rawValue]
}
else { hostname = [domainName.rawValue, domainExtension.rawValue] }
urlComponents.host = hostname.joined(separator: ".")
//Create URL and add path components if any exist
var url = urlComponents.url
if let pathComponents = pathComponents {
for pathComponent in pathComponents {
url?.appendPathComponent(pathComponent.rawValue)
}
}
//Create URL string
guard let urlString = url?.absoluteString else {
return nil
}
//Use existing initialiser with the string
self.init(string: urlString)
}
}
//URL with path components
let appleURL = URL(scheme: .https, domainName: .apple, domainExtension: .com, pathComponents: [.accessibility])
//URL with subdomain
let googleURL = URL(scheme: .https, subdomain: .maps, domainName: .google, domainExtension: .com)
//URL without either
let googleUKURL = URL(scheme: .https, domainName: .google, domainExtension: .couk)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment