Introducing URLQueryItemEncoder

Pitiphong Phongpattranont
Pitiphong’s blog
Published in
2 min readOct 26, 2017

--

The Swift Evolution 0166 Swift Archival & Serialization laid out a great foundation for doing the serialization for Swift types and also has a separate mechanism for type to define how it should be archived from the mechanism to serialize those value into any format. When I saw this proposal in action in Swift 4, I had an idea to implement an encoder for one of the common use cases in the internet, a URL Query Item Encoder.

The URLQueryItemEncoder encoder will encode the encodable value into an array of `URLQueryItem` and we can use that array later with the URLComponents API. The URLQueryItemEncoder comes with a simple and familiar API with 1 strategy option for specify how to encode the array index key.

You can try it at its GitHub repo and please feel free to give me a feedback. And if you find this API useful, please help me share it.

Example

var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(identifier: "UTC")!

var urlComponents = URLComponents(string: "https://api.github.com/repos/pitiphong-p/URLQueryItemEncoder/issues/comments")!
let parameter = GithubListCommentParameter(
sort: (.created, .ascending),
since: calendar.date(from: DateComponents(year: 2017, month: 10, day: 27))!
)
let encoder = URLQueryItemEncoder()
let items = try encoder.encode(parameter)
urlComponents.queryItems = items

// urlComponents.url = "https://api.github.com/repos/pitiphong-p/URLQueryItemEncoder/issues/comments?sort=created&direction=asc&since=2017-10-27T00:00:00Z"

Here’s a code snippet of the `GitHubListCommentParameter` data type in the above example. In case you want to try it in the Playground. You can look at its GitHub API page for more information about this type.

struct GitHubListCommentParameter: Encodable {
enum Sort: String, Encodable {
case created
case updated
}
enum Direction: String, Encodable {
case ascending = "asc"
case descending = "des"
}

let sort: (Sort, Direction?)
let since: Date

private enum CodingKeys: String, CodingKey {
case sort
case direction
case since
}

func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(sort.0, forKey: .sort)
try container.encodeIfPresent(sort.1, forKey: .direction)
try container.encode(since, forKey: .since)
}
}

--

--

A long time iOS Developer who also interested on the Programming, User Interface and User Experience design. Want to see my code? https://github.com/pitiphong-p