Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of optional type String must be unwrapped to a value type of String? [duplicate]

Tags:

ios

swift

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.

like image 708
MoreSushiPlease Avatar asked Jun 03 '19 22:06

MoreSushiPlease


People also ask

What should we use for unwrapping value inside optional?

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.

How many ways unwrap optional?

You can unwrap optionals in 4 different ways: With force unwrapping, using ! With optional binding, using if let. With implicitly unwrapped optionals, using !


2 Answers

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:

  1. 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.

  2. 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.

like image 65
Vlad Rusu Avatar answered Sep 21 '22 13:09

Vlad Rusu


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!"
like image 26
Sh_Khan Avatar answered Sep 21 '22 13:09

Sh_Khan