Skip to content

Instantly share code, notes, and snippets.

@benjaminsnorris
Created March 8, 2016 20:44
Show Gist options
  • Save benjaminsnorris/86648135d2322e6de7ec to your computer and use it in GitHub Desktop.
Save benjaminsnorris/86648135d2322e6de7ec to your computer and use it in GitHub Desktop.
Flag Emoji
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") // 🇯🇵
@AliSoftware
Copy link

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 😞

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