Skip to content

Instantly share code, notes, and snippets.

@douglashill
Created January 14, 2023 18:24
Show Gist options
  • Save douglashill/719561fe916cb19bf2cabc8649cbc28e to your computer and use it in GitHub Desktop.
Save douglashill/719561fe916cb19bf2cabc8649cbc28e to your computer and use it in GitHub Desktop.
Splits a URL that might have a fragment into the URL with the fragment removed and the fragment text.
extension URL {
/// Splits a URL that might have a fragment into the URL with the fragment removed and the fragment text.
///
/// If there is no fragment in the URL, this will return a URL identical to the receiver and nil.
///
/// Example input: https://github.com/douglashill/KeyboardKit/blob/main/Features.md#date-picker
/// Example output: (https://github.com/douglashill/KeyboardKit/blob/main/Features.md, date-picker)
func extractFragment() -> (urlWithoutFragment: URL, fragment: String?) {
guard var components = URLComponents(url: self, resolvingAgainstBaseURL: false) else {
logError("Couldn’t create URL components from URL in order to extract fragment.")
return (self, nil)
}
let fragment = components.fragment
components.fragment = nil
guard let urlWithoutFragment = components.url else {
logError("Couldn’t create URL from URL components in order to remove fragment.")
return (self, nil)
}
return (urlWithoutFragment, fragment)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment