Skip to content

Instantly share code, notes, and snippets.

@aainaj
Last active April 3, 2020 03:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aainaj/bc9c8b5be58f307c1287fc1b77b20aad to your computer and use it in GitHub Desktop.
Save aainaj/bc9c8b5be58f307c1287fc1b77b20aad to your computer and use it in GitHub Desktop.
URL Builder Pattern
protocol ScopeFunc {}
extension ScopeFunc {
@inline(__always) func apply(block: (Self) -> ()) -> Self {
block(self)
return self
}
}
class URLBuilder: ScopeFunc {
private var components = URLComponents()
func set(scheme: String) -> URLBuilder {
self.components.scheme = scheme
return self
}
func set(host: String) -> URLBuilder {
apply { $0.components.host = host }
}
func set(port: Int) -> URLBuilder {
apply { $0.components.port = port }
}
func set(path: String) -> URLBuilder {
var path = path
if !path.hasPrefix("/") {
path = "/" + path
}
self.components.path = path
return self
}
func addQueryItem(name: String, value: String) -> URLBuilder {
if self.components.queryItems == nil {
self.components.queryItems = []
}
self.components.queryItems?.append(URLQueryItem(name: name, value: value))
return self
}
func build() -> URL? {
return self.components.url
}
}
let url = URLBuilder()
.set(scheme: "https")
.set(host: "localhost")
.set(path: "api/v1")
.addQueryItem(name: "sort", value: "name")
.addQueryItem(name: "order", value: "asc")
.build()
print(url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment