I'm confused. Could someone please tell me why I get a "No exact matches in call to initializer" error when I have this code....
let bill = textField.text
let billTotal = Double(bill)
but when I force unwrap textField.text the error goes away and everything is good...
let bill = textField.text!
let billTotal = Double(bill)
My thinking is that it should still work without force unwrapping but the app will crash if the textField is nil.
Also, why can I not use an optional instead of force unwrapping?
let bill = textField.text?
let billTotal = Double(bill)
Using an optional gives me the same error: "No exact matches in call to initializer"
Using an optional gives me the same error: "No exact matches in call to initializer" Show activity on this post. The error occurs because text is an optional and the initializer parameter must be non-optional.
Another more Swifty way, is using description because Int conforms to CustomStringConvertible protocol. You can create your own initialiser for Text if this a common use case for you, using Swift's string interpolation. This may reduce type visibility at the call-site however.
Using an optional gives me the same error: "No exact matches in call to initializer" Show activity on this post. The error occurs because text is an optional and the initializer parameter must be non-optional. My thinking is that it should still work without force unwrapping but the app will crash if the textField is nil.
The error occurs because text is an optional and the initializer parameter must be non-optional. My thinking is that it should still work without force unwrapping but the app will crash if the textField is nil.
The error occurs because text
is an optional and the initializer parameter must be non-optional.
My thinking is that it should still work without force unwrapping but the app will crash if the textField is nil.
In this case force unwrapping is fine because the text
property of a UITextField
is never nil
although it's declared as optional.
But instead you should check the created Double
because the entered text might be not convertible to Double
, either with a default value
let billTotal = Double(textField.text!) ?? 0.0
or providing a more advanced error handling
if let billTotal = Double(textField.text!) {
// do something with billTotal
} else {
// handle the error
}
textField.text
already an optional.. you can do
if let bill = textField.text {
let billTotal = Double(bill)
}
Also you can do that by suggested By @Jessy Thanks ...
let billTotal = textField.text.flatMap(Double.init)
To convert in Double .. its inializer takes S : StringProtocol
which confirm StringProtocol
... Only the String
and
Substring
types in the standard library are valid conforming types not Optional String
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With