Reworked @matt answer with an extension:
extension URLComponents {
init(from url: URL) throws {
guard let scheme = url.scheme else {
throw URLError(.badURL, userInfo: [NSLocalizedDescriptionKey: "`\(url)` has no scheme"])
}
guard let host = url.host else {
throw URLError(.badURL, userInfo: [NSLocalizedDescriptionKey: "`\(url)` has no host"])
}
var path = url.absoluteString.components(separatedBy: host).last ?? ""
if path.hasSuffix("/") {
path.removeLast()
}
self.init()
self.scheme = scheme
self.host = host
if !path.isEmpty {
self.path.append(path)
}
}
}