Skip to content

Instantly share code, notes, and snippets.

@CanTheAlmighty
Created November 28, 2016 14:34
Show Gist options
  • Save CanTheAlmighty/3d403ec3cc3441caf2a3df8cc6f4799c to your computer and use it in GitHub Desktop.
Save CanTheAlmighty/3d403ec3cc3441caf2a3df8cc6f4799c to your computer and use it in GitHub Desktop.
Provides Keyword-formatting to the String class
String(format: "The value of life is %(life)$d", ["life":42])
// "The value of life is 42"
String(format: "¿Dónde está %(firstname)$@ %(lastname)$@?", ["firstname":"Carmen", "lastname":"San Diego"])
// "¿Dónde está Carmen San Diego?"
String(format: "PI is %(pi)$.4f", ["pi":Double.pi])
// "PI is 3.1416"
String(format: "But PI can also be %(pi)$.f, or %(pi)$.5f, depending how you format it", ["pi":Double.pi])
// "But PI can also be 3, or 3.14159, depending how you format it"
String(format: "😇😍%(emoji)$@", ["emoji":"😁"])
// "😇😍😁"
import Foundation
public extension String
{
// Look for %(word)$ and replace it
private static let __keywordRegexp = try! NSRegularExpression(pattern: "%\\((.+?)\\)\\$", options: [])
public init(format text: String, _ keywords: [String : CVarArg])
{
// Matches for %(value)$, capturing
let range = NSRange(location: 0, length: (text as NSString).length)
// Results
var keys : [String] = []
// Save all the captures
for match in String.__keywordRegexp.matches(in: text, options: [], range: range)
{
keys.append((text as NSString).substring(with: match.rangeAt(1)))
}
// Create the final format string
let format = String.__keywordRegexp.stringByReplacingMatches(in: text, options: [], range: range, withTemplate: "%")
self.init(format: format, arguments: keys.map { keywords[$0] }.flatMap { $0 })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment