0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Swift] URLから特定のクエリパラメータを除去するextension

Last updated at Posted at 2021-04-09

表題のような処理がしたくて、URLのextensionを作ってみました。

たぶん、あまり需要はないと思うのですが。笑

環境:
Xcode 12.1 / Swift 5.3

playground
import Foundation

extension URL {
    /// URLからクエリパラメータを除去する
    /// - Parameter name: パラメータ名
    /// - Returns: 新しいURLオブジェクト
    func removeQueryItem(_ name: String) -> URL? {
        guard var component = URLComponents(url: self, resolvingAgainstBaseURL: false) else {
            return nil
        }
        component.queryItems = component.queryItems?.compactMap { item -> URLQueryItem? in
            return item.name == name ? nil : item
        }
        if let queryItems = component.queryItems, queryItems.isEmpty {
            component.queryItems = nil
        }
        return component.url
    }
}

// 使い方
// クエリパラメータ"foo"を削除
let url_1 = URL(string: "https://qiita.com/search?q=swift&foo=bar")
print("\(url_1!.removeQueryItem("foo")!.absoluteString)")
// https://qiita.com/search?q=swift

// アンカーがある場合
let url_2 = URL(string: "https://qiita.com/y-some/items/200db9ac37150effc8ed?foo=var#swift")
print("\(url_2!.removeQueryItem("foo")!.absoluteString)")
// https://qiita.com/y-some/items/200db9ac37150effc8ed#swift

// クエリパラメータがない場合(何もしない)
let url_3 = URL(string: "https://qiita.com/")
print("\(url_3!.removeQueryItem("foo")!.absoluteString)")
// https://qiita.com/
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?