I'm very new to Swift and unfortunately I can't get any further with a problem.
I have the problem that the error below occurs when reading a text field that can only contain numbers.
I use the decimal pad with German localization on the keyboard for "myTextField". This means that a comma is entered instead of a period. That's probably where the error is. How can I solve the problem that does not occur with integers.
Thanks for the support.
@IBOutlet weak var myTextField: UITextField!
var myVariable : Double = 0.0
myVariable = Double(myTextField.text!)!
Error message: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
It took a while because my English isn't the best either.
With the help of apple and some manuals I got around to it and hope to have found the right way:
let newVariable = NumberFormatter()
newVariable.numberStyle = .decimal
newVariable.locale = Locale(identifier: "de_DE")
newVariable.number(from: myTextField.text!)
if let x = newVariable.number(from: myTextField.text!) {
myVariable = x.doubleValue
}
Sure, if you can figure out how to use format styles (-: But keep in mind that Jörg wants to parse, not format, and that calls for FloatingPointParseStrategy:
let en = Locale(identifier: "en_AU")
let enFS = FloatingPointFormatStyle<Double>(locale: en)
let enPS = FloatingPointParseStrategy(format: enFS, lenient: true)
let enD = try enPS.parse("3.141")
print(enD) // 3.141
let de = Locale(identifier: "de_DE")
let deFS = FloatingPointFormatStyle<Double>(locale: de)
let dePS = FloatingPointParseStrategy(format: deFS, lenient: true)
let deD = try dePS.parse("2,718")
print(deD) // 2.718