简体   繁体   中英

Value of type 'String' has no member 'substringToIndex' not resolved

I am trying to grab currentLanguage of a device using the below function. But there has been an issue with substring and I don't seem to understand as previous answers have such simple solution of importing Foundation to the file, which didn't work for me.

class func currentLanguage() -> String
{
    let str = "en-US"       
    if let indexOfDash = str.characters.index(of: "-")
    {
        let langCode = str.substringToIndex(indexOfDash)

        return langCode
    }
}

In addition, What can be the best approach to get current language?

You need to use

let langCode = str.substring(to: indexOfDash)

And you can get current language like that:

let pre = NSLocale.preferredLanguages[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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