Created
August 10, 2018 15:34
-
-
Save markiv/a8b81002d66c93de4a67507c83fcf95e to your computer and use it in GitHub Desktop.
Useful URL extensions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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