Created
March 8, 2016 20:44
-
-
Save benjaminsnorris/86648135d2322e6de7ec to your computer and use it in GitHub Desktop.
Flag 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
struct FlagEmoji { | |
private static let regionalIndicatorA: UInt32 = 0x1F1E6 | |
| |
enum Error: ErrorType { | |
case ExpectedOnlyAZ | |
} | |
| |
private static func toRegionalIndicator(scalar: UnicodeScalar) throws -> UnicodeScalar { | |
let offset: UInt32 | |
switch scalar { | |
case "A"..."Z": offset = scalar.value - "A".unicodeScalars.first!.value | |
case "a"..."z": offset = scalar.value - "a".unicodeScalars.first!.value | |
default: throw Error.ExpectedOnlyAZ | |
} | |
return UnicodeScalar(regionalIndicatorA + offset) | |
} | |
static func fromISO3166Code(iso3166Code: String) throws -> String { | |
return try iso3166Code.unicodeScalars | |
.map(toRegionalIndicator) | |
.map { String($0) } | |
.joinWithSeparator("") | |
} | |
} | |
| |
try? FlagEmoji.fromISO3166Code("FR") // 🇫🇷 | |
try? FlagEmoji.fromISO3166Code("US") // 🇺🇸 | |
try? FlagEmoji.fromISO3166Code("IE") // 🇮🇪 | |
try? FlagEmoji.fromISO3166Code("JP") // 🇯🇵 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, it would have been cool if you at least credited me for this snippet instead of just copy/pasting my code from Slack here in your gist 😞