Detect Language of NSString

后端 未结 6 1053
鱼传尺愫
鱼传尺愫 2020-11-27 11:39

Somebody told me about a class for language recognition in Cocoa. Does anybody know which one it is?

This is not working:

NSSpellCh         


        
6条回答
  •  渐次进展
    2020-11-27 12:34

    As of iOS 11 you can use the dominantLanguage(for:)/dominantLanguageForString: class method of NSLinguisticTagger.

    Swift:

    extension String {
        var language: String? {
            return NSLinguisticTagger.dominantLanguage(for: self)
        }
    }
    
    print("Good morning".language)
    print("Buenos días".language)
    

    Objective-C:

    @interface NSString (Tagger)
    
    @property (nonatomic, readonly, nullable) NSString *language;
    @end
    
    @implementation NSString (Tagger)
    
    - (NSString *)language {
        return [NSLinguisticTagger dominantLanguageForString:self];
    }
    
    @end
    
    NSLog(@"%@", @"Good morning".language);
    NSLog(@"%@", @"Buenos días".language);
    

    Output (for both):

    en
    es

提交回复
热议问题