简体   繁体   English

类型“ NSLinguisticTag”的值没有成员“ range”

[英]Value of type 'NSLinguisticTag' has no member 'range'

I have text direction code its working good with swift 3 but after migration to swift 4, I got error 我有文本方向代码,可以在Swift 3上正常工作,但是在迁移到Swift 4之后,出现了错误

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
    }

Anyone know how to fix this? 有人知道怎么修这个东西吗? thanks 谢谢

As of Swift 4, NSLinguisticTagger returns tags not as (optional) strings, but as (optional) values of NSLinguisticTag : 从Swift 4开始, NSLinguisticTagger返回的标签不是(可选)字符串,而是NSLinguisticTag (可选)值:

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

You get the underlying string with the rawValue property: 您将获得带有rawValue属性的基础字符串:

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

If you want to check for equality and not for containment then you can also define your own NSLinguisticTag constants: 如果要检查相等性而不是包含性,则还可以定义自己的NSLinguisticTag常量:

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

and use them as 并将它们用作

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

Another option would be to define a custom computed property 另一个选择是定义自定义计算属性

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

and use it as 并用作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM