Skip to content

Instantly share code, notes, and snippets.

@TheWorstProgrammerEver
Last active March 5, 2022 07:56
Show Gist options
  • Save TheWorstProgrammerEver/920716acc604be2ef33095d04ac32432 to your computer and use it in GitHub Desktop.
Save TheWorstProgrammerEver/920716acc604be2ef33095d04ac32432 to your computer and use it in GitHub Desktop.
Type-driven URL templating in Swift
import Foundation
struct StringTemplate<T> {
var template: String
init(_ template: String) {
self.template = template
}
func fill(_ t: T) -> String {
Mirror(reflecting: t).children.reduce(template) { (acc, next) in
acc.replacingOccurrences(of: "{\(next.label!)}", with: "\(next.value)")
}
}
}
struct LMGTFY {
var query: String
var random: Int
}
var letMeGoogleBananasForYou = StringTemplate<LMGTFY>("https://lmgtfy.app/?q={query}&random={random}")
.fill(.init(query: "Bananas", random: 123))
print(letMeGoogleBananasForYou)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment