1
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 1 year has passed since last update.

【Swift】URLRequestのHttpMethodをenumで設定する

Last updated at Posted at 2023-07-19

URLReqeustのHttpMethodは、なぜかenumではなくStringで設定する仕様になっている。
なんか気持ち悪いので extension 作りました

Before

POSTリクエストを作りたい場合、こうやって記述する。

let url = URL(string: "https://hoge.com")!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"

なぜこんな仕様にした・・・?

いざextension

URLRequestをextensionしてenumHttpMethodとメソッドhttpMethodを定義する

import Foundation

extension URLRequest {
    enum HttpMethod: String {
        case GET
        case POST
        case PATCH
        case PUT
        case DELETE
    }
    
    mutating func httpMethod(_ method: HttpMethod) {
        httpMethod = method.rawValue
    }
}

After

let url = URL(string: "https://hoge.com")!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod(.POST)

あとがき

これで気持ちよくPOSTできるね

1
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
1
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?