Swift turn a country code into a emoji flag via unicode

后端 未结 7 890
日久生厌
日久生厌 2020-12-07 14:08

I\'m looking for a quick way to turn something like:

let germany = \"DE\" 

into

let flag = \"\\u{1f1e9}\\u{1f1ea}\"
         


        
7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-07 14:24

    If anyone looking for solution in ObjectiveC here is convenient category:

    @interface NSLocale (RREmoji)
    
    + (NSString *)emojiFlagForISOCountryCode:(NSString *)countryCode;
    
    @end
    
    
    @implementation NSLocale (RREmoji)
    
    
    + (NSString *)emojiFlagForISOCountryCode:(NSString *)countryCode {
        NSAssert(countryCode.length == 2, @"Expecting ISO country code");
    
        int base = 127462 -65;
    
        wchar_t bytes[2] = {
            base +[countryCode characterAtIndex:0],
            base +[countryCode characterAtIndex:1]
        };
    
        return [[NSString alloc] initWithBytes:bytes
                                        length:countryCode.length *sizeof(wchar_t)
                                      encoding:NSUTF32LittleEndianStringEncoding];
    }
    
    
    @end
    

    test:

    for ( NSString *countryCode in [NSLocale ISOCountryCodes] ) {
        NSLog(@"%@ - %@", [NSLocale emojiFlagForISOCountryCode:countryCode], countryCode);
    }
    

    output:

提交回复
热议问题