Last active
April 3, 2020 03:28
-
-
Save aainaj/bc9c8b5be58f307c1287fc1b77b20aad to your computer and use it in GitHub Desktop.
URL Builder Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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