Skip to content

Instantly share code, notes, and snippets.

@takasek
Created July 11, 2020 13:04
Show Gist options
  • Save takasek/51e61c1fbd10c5bfc51b1c2cbd5a096c to your computer and use it in GitHub Desktop.
Save takasek/51e61c1fbd10c5bfc51b1c2cbd5a096c to your computer and use it in GitHub Desktop.
さっきの https://anoqode.com/question?id=9dd1d9f9-bba9-4cde-b331-1ab78b155b01 ですけど、RawRepresentableなstructを噛ませておくと、失敗した文字列も失わずに済むので好きです #swiftzoomin #CodePiece
let jsonData = """
[
"https://www.apple.com",
"https://swift.org/blog/",
"https://github.com/apple/swift/releases/tag/swift 5.2.4-RELEASE"
]
"""
.data(using: .utf8)!
struct SafeURL: RawRepresentable, Decodable {
let rawValue: String
var url: URL? { URL(string: rawValue) }
}
let urls = try JSONDecoder().decode([SafeURL].self, from: jsonData)
urls.map(\.url)
// [https://www.apple.com, https://swift.org/blog/, nil]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment