I'm new to iOS development. I'm practicing linking actions/outlets between the View and Controller. My problem is that I don't know why it shows me some errors. Could you please take a look at my code and tell me what I'm missing?
I receive the following errors:
Value of optional type 'String?' must be unwrapped to a value of type 'String'
Coalesce using '??' to provide a default when the optional value contains 'nil'
Force-unwrap using '!' to abort execution if the optional value contains 'nil'
Here's the code:
@IBAction func submitAppointmentDetails(_ sender: Any) {
appointmentSetName.text = "Congratulations," + nameField.text + "You have now set up an appointment with us!"
}
A photo of what's going on: https://imgur.com/a/WKT4EyE
Edit: @matt This is a different question because the thread you thought this is a duplicate of doesn't have the solution that I was seeking, but two people in this thread did give me the solution. I never would have found the solution if I just read the thread that you shared.
A common way of unwrapping optionals is with if let syntax, which unwraps with a condition. If there was a value inside the optional then you can use it, but if there wasn't the condition fails. For example: if let unwrapped = name { print("\(unwrapped.
You can unwrap optionals in 4 different ways: With force unwrapping, using ! With optional binding, using if let. With implicitly unwrapped optionals, using !
nameField.text
is of type String?
meaning it is an optional string (it may contain a String
or nil
). Swift doesn't allow you to concatenate optional strings. You have to unwrap the value and you basically have the Swift's proposed ways you have put in the question:
You can force unwrap the string nameField.text!
. With this you tell Swift 'get the string value from that optional, I'm sure it's not nil
', but this will crash the app if it's nil
.
You can use the coalesce operator ??
this way nameField.text ?? "<no_name>"
. This will do the following: if nameField.text
is not nil
, then the text will be displayed correctly; if nameField.text
is nil, the "<no_name>"
string will be displayed instead.
nameField.text
gives an optional string so to concatenate it Replace
appointmentSetName.text = "Congratulations," + nameField.text + "You have now set up an appointment with us!"
with
appointmentSetName.text = "Congratulations," + nameField.text! + "You have now set up an appointment with us!"
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