Created
November 28, 2016 14:34
-
-
Save CanTheAlmighty/3d403ec3cc3441caf2a3df8cc6f4799c to your computer and use it in GitHub Desktop.
Provides Keyword-formatting to the String class
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
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":"😁"]) | |
// "😇😍😁" |
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 | |
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