LoginSignup
0
1

More than 1 year has passed since last update.

【Swift】URLはStringからデコードできる

Posted at

偶然気づいたのですが、JSONをデコードする際にURLは直接Stringからデコードできるみたいです。

例えばこういうJSONがあったとします。

let jsonString = """
{
    "url": "https://example.com/",
}
"""

この時に作成するモデルは

struct Example: Decodable {
    let url: URL
}

と書く事ができます。let url: Stringとしなくても良いという事です。

試しにデコードしてみます。

let example = try JSONDecoder().decode(Example.self, from: jsonString.data(using: .utf8)!)

// Example(url: https://example.com/)
print(example)
// URL
print(type(of: example.url))

どうやらちゃんとURL型にデコードされているみたいです。

今度は不当なStringを与えてみます。

let jsonString = """
{
    "url": " ",
}
"""
struct Example: Decodable {
    let url: URL
}

let example = try JSONDecoder().decode(Example.self, from: jsonString.data(using: .utf8)!)
Playground execution terminated: An error was thrown and was not caught:
▿ DecodingError
  ▿ dataCorrupted : Context
    ▿ codingPath : 1 element
      - 0 : CodingKeys(stringValue: "url", intValue: nil)
    - debugDescription : "Invalid URL string."
    - underlyingError : nil

デコードエラーとなりました。ちゃんと確認はしてませんが、このバリデーションはURL.init(string:)と同じかもしれません。

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