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