Skip to content

Instantly share code, notes, and snippets.

@codyrobb
Created November 22, 2016 20:24
Show Gist options
  • Save codyrobb/03baa82e9f45b77887b07d879d40c231 to your computer and use it in GitHub Desktop.
Save codyrobb/03baa82e9f45b77887b07d879d40c231 to your computer and use it in GitHub Desktop.
class Phrase {
// MARK: -
// MARK: Properties
private let template: String
private var lookup: [String: String] = [:]
// MARK: -
// MARK: Initialization
init(template: String) {
self.template = template
}
// MARK: -
// MARK: Public
func put(key: String, value: String) -> Phrase {
lookup[key] = value
return self
}
func format() -> String {
var formatted = template
for (key, value) in lookup {
formatted = formatted.replacingOccurrences(of: tokenize(key: key), with: value)
}
return formatted
}
// MARK: -
// MARK: Private
private func tokenize(key: String) -> String {
return "{" + key + "}"
}
}
@codyrobb
Copy link
Author

Example Usage:

let template = "Hi {first_name}, you are {age} uears old."
let formatted = Phrase(template: template)
    .put(key: "first_name", value: "Cody Robertson")
    .put(key: "age", value: "23")
    .format()

print(template)   // prints: "Hi {first_name}, you are {age} uears old."
print(formatted) // prints: "Hi Cody Robertson, you are 23 uears old."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment