Last active
March 5, 2022 07:56
-
-
Save TheWorstProgrammerEver/920716acc604be2ef33095d04ac32432 to your computer and use it in GitHub Desktop.
Type-driven URL templating in Swift
This file contains hidden or 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 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