Created
June 7, 2023 14:34
-
-
Save fitomad/611c91cedc6576bb288a6f76d6d2ee74 to your computer and use it in GitHub Desktop.
A Swift's parameter packs new feature example
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
import Foundation | |
struct Query<Element> { | |
let key: String | |
let value: Element | |
var filter: String { | |
return "\(key)=\(String(describing: value))" | |
} | |
} | |
// | |
// The parameter packs in action | |
// | |
func query<each Filter>(_ parameter: repeat Query<each Filter>) -> String { | |
// For each parameter received, obtain the `filter` property value | |
let filters = (repeat (each parameter).filter) | |
// Let's iterate over tuple and cast the values to strings | |
let mirror = Mirror(reflecting: filters) | |
let filter = mirror.children | |
.map({ String(describing: $0.value) }) | |
.joined(separator: "&") | |
return filter | |
} | |
// MARK: - Make some tests | |
let apiKey = Query(key: "api_key", value: "fasd_esp_00197500") | |
let currentPage = Query(key: "page", value: 1) | |
let offset = Query(key: "offset", value: 100) | |
let adultContent = Query(key: "includes_adult_content", value: false) | |
let firstQueryFilter = query(apiKey, offset, adultContent) | |
print(firstQueryFilter) | |
let nextQueryFilter = query(apiKey, currentPage, offset, adultContent) | |
print(nextQueryFilter) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment