Skip to content

Instantly share code, notes, and snippets.

@douglashill
Created January 14, 2023 18:24
Show Gist options
  • Select an option

  • Save douglashill/719561fe916cb19bf2cabc8649cbc28e to your computer and use it in GitHub Desktop.

Select an option

Save douglashill/719561fe916cb19bf2cabc8649cbc28e to your computer and use it in GitHub Desktop.

Revisions

  1. douglashill created this gist Jan 14, 2023.
    23 changes: 23 additions & 0 deletions URL+ExtractFragment.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    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)
    }
    }