0

I am trying to find out the current used language in my app as in this link:

How to get current language code with Swift?

     let pre = Locale.preferredLanguages[0]

but it's keep crashing and got this error:

enter image description here

How to solve this and why am getting this error?

this only happens in classes like:

class ButtonText: UIButton {
    let padding = UIEdgeInsets(top: 0, left: 35, bottom: 0, right: 0);
    let padding2 = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 35);
    let pre = Locale.preferredLanguages[0]

    override open func titleRect(forContentRect bounds: CGRect) -> CGRect {
        //if pre != "ar"{
        if let code = Locale.current.languageCode , code != "ar" {
            return UIEdgeInsetsInsetRect(bounds, padding)
        }else {
            titleLabel?.textAlignment = .left
            return UIEdgeInsetsInsetRect(bounds, padding2)
        }
        /* }else{
         titleLabel?.textAlignment = .left
         return UIEdgeInsetsInsetRect(bounds, padding2)
         }*/
    }
}
Anton Belousov
  • 1,140
  • 15
  • 34
mrs.bassim
  • 469
  • 2
  • 7
  • 16

1 Answers1

1

Your code in image have no error we need previous code and how you use this button to know where is exception

Current languageCode with this line is optional string

Locale.current.languageCode

but with this line is not optional

Locale.preferredLanguages[0]

So try this and tell me result

 override func titleRect(forContentRect contentRect: CGRect) -> CGRect {

    if let code = Locale.current.languageCode , code != "en" {

    } else{

    }
}
Abdelahad Darwish
  • 5,969
  • 1
  • 17
  • 35