Found this, it will only be helpful you are going to use NSLocalizedString in side classes.
tested it on swift 4 with the following tweaks
extension NSObject {
func NSLocalizedString(_ key: String, comment: String) -> String {
return "My custom localization"
}
static func NSLocalizedString(_ key: String, comment: String) -> String {
return "My custom localization"
}
}
class ViewController: UIViewController {
@IBOutlet weak var myLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
myLabel.text = NSLocalizedString("mystring",comment:"")
}
}
should work the same for swift 2.3 (without the underscore before the key
param)
Update
This needs a workaround when working with closures, because swift will expect of you to use the NSLocalizedString
with self
like so, self.NSLocalizedString("mystring",comment:"")
.
The workaround in this scenario is to assign the string to a let
/var
outside the closure.
Example:
// Doesn't work
self.present(anotherVc, animated: true) { [weak self] in
self?.myLabel.text = NSLocalizedString("mystring", comment: "") // compiler will throw an error
}
// Does work
let string = NSLocalizedString("mystring", comment: "")
self.present(anotherVc, animated: true) { [weak self] in
self?.myLabel.text = string
}
For property initializers the compiler will use the static function, that's why it's important to set them both
Example:
class MyClass: NSObject {
// This let
let myStr = NSLocalizedString("mystring",comment:"")
}
extension NSObject {
func NSLocalizedString(_ key: String, comment: String) -> String {
return "My custom localization"
}
// Uses the static method
static func NSLocalizedString(_ key: String, comment: String) -> String {
return "My custom localization"
}
}