Skip to content

Instantly share code, notes, and snippets.

@markiv
Created August 10, 2018 15:34
Show Gist options
  • Save markiv/a8b81002d66c93de4a67507c83fcf95e to your computer and use it in GitHub Desktop.
Save markiv/a8b81002d66c93de4a67507c83fcf95e to your computer and use it in GitHub Desktop.
Useful URL extensions
extension URL {
typealias ComponentsManipulator = (inout URLComponents) -> ()
func manipulate(with manipulator: ComponentsManipulator) -> URL {
guard var components = URLComponents(url: self, resolvingAgainstBaseURL: true) else { return self }
manipulator(&components)
return components.url ?? self
}
/// Deletes first path component after the initial slash
/// For example, path /en/v1/sync/categories becomes /v1/sync/categories
func deletingFirstPathComponent() -> URL {
return manipulate { components in
components.path = "/" + pathComponents.dropFirst().dropFirst().joined(separator: "/") // drop initial "/" first
}
}
/// Adds or replaces a query parameter
func settingParameter(named name: String, to value: CustomStringConvertible) -> URL {
return manipulate { components in
var items = components.queryItems?.filter { $0.name != name } ?? []
items.append(URLQueryItem(name: name, value: String(describing: value)))
components.queryItems = items
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment