I\'ve already seen two similar questions to mine, but the answers for those questions do not work for me. I have an old project with a list of countries manually typed out insid
Swift You can easily retrieve countries name and their flags emoji.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var countriesData = [(name: String, flag: String)]()
for code in NSLocale.isoCountryCodes {
let flag = String.emojiFlag(for: code)
let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
if let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) {
countriesData.append((name: name, flag: flag!))
}else{
//"Country not found for code: \(code)"
}
}
print(countriesData)
}
}
extension String {
static func emojiFlag(for countryCode: String) -> String! {
func isLowercaseASCIIScalar(_ scalar: Unicode.Scalar) -> Bool {
return scalar.value >= 0x61 && scalar.value <= 0x7A
}
func regionalIndicatorSymbol(for scalar: Unicode.Scalar) -> Unicode.Scalar {
precondition(isLowercaseASCIIScalar(scalar))
// 0x1F1E6 marks the start of the Regional Indicator Symbol range and corresponds to 'A'
// 0x61 marks the start of the lowercase ASCII alphabet: 'a'
return Unicode.Scalar(scalar.value + (0x1F1E6 - 0x61))!
}
let lowercasedCode = countryCode.lowercased()
guard lowercasedCode.count == 2 else { return nil }
guard lowercasedCode.unicodeScalars.reduce(true, { accum, scalar in accum && isLowercaseASCIIScalar(scalar) }) else { return nil }
let indicatorSymbols = lowercasedCode.unicodeScalars.map({ regionalIndicatorSymbol(for: $0) })
return String(indicatorSymbols.map({ Character($0) }))
}
}
Result: