2017-08-24 32 views
1

我有文字指示碼其工作良好,快捷3,但遷移到SWIFT 4後,我得到了錯誤類型的值「NSLinguisticTag」沒有成員「範圍」

let tagScheme = [NSLinguisticTagScheme.language] 
    let tagger = NSLinguisticTagger(tagSchemes: tagScheme, options: 0) 
    tagger.string = self.text 
    let lang  = tagger.tag(at: 0, scheme: NSLinguisticTagScheme.language, 
             tokenRange: nil, sentenceRange: nil) 

    if lang?.range(of: "he") != nil || lang?.range(of: "ar") != nil { //Value of type 'NSLinguisticTag' has no member 'range' 
     self.textAlignment = NSTextAlignment.right 
    } else { 
     self.textAlignment = NSTextAlignment.left 
    } 

任何人都知道如何解決這一問題?感謝

回答

1

隨着斯威夫特4,NSLinguisticTagger回報標籤不是(可選) 字符串,但作爲(可選)值NSLinguisticTag的:

public struct NSLinguisticTag : RawRepresentable, Equatable, Hashable { 
    public init(_ rawValue: String) 
    public init(rawValue: String) 
} 

你獲得與rawValue屬性的基礎字符串:

if let lang = tagger.tag(at: 0, scheme: .language, tokenRange: nil, sentenceRange: nil) { 
    print(lang.rawValue) 
    if lang.rawValue.hasPrefix("he") { ... } 
} 

如果你想檢查是否相等,而不是包含然後 你也可以定義你自己的NSLinguisticTag常量:

extension NSLinguisticTag { 
    static let hebrew = NSLinguisticTag("he") 
} 

,並把它們作爲

if let lang = tagger.tag(at: 0, scheme: .language, tokenRange: nil, sentenceRange: nil) { 
    if lang == .hebrew { ... } 
} 

另一種選擇是,來定義計算的屬性

extension NSLinguisticTag { 
    var isRightToLeft: Bool { 
     return rawValue.hasPrefix("he") || rawValue.hasPrefix("ar") 
    } 
} 

,並用它作爲

if let lang = tagger.tag(at: 0, scheme: .language, tokenRange: nil, sentenceRange: nil) { 
    if lang.isRightToLeft { ... } 
} 
相關問題