79700169

Date: 2025-07-13 18:29:14
Score: 1
Natty:
Report link

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)
    }
  }
}
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @matt
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: Ihar