Value of optional string must be unwrapped

Hello Codecademy Forums!

I’m trying to learn Swift and I’m running into an error that I can’t figure out and I hope someone can help me better understand the concept of optionals. In the code below, I’m just trying to do something very simple; randomly select a string from an array and return it.

However, when I try and run the code in Xcode, it gives me the following error - “Value of optional type ‘String?’ must be unwrapped to a value of type ‘String’”. I’ve watched a couple videos on optionals, but something is obviously going over my head. Why does Xcode think that I want to return an optional?

func genNumofParameters() -> String {

let parameterOption = ["One", "Two", "Three"]
let selectedOption = parameterOption.randomElement()
return selectedOption
}

Thank you for any pointers.

Hi @twoforflinching,

You can unwrap an optional variable value by adding a ! at the end of the optional variable to unwrap it to get the original value.

func genNumofParameters() -> String {
  let parameterOption = ["One", "Two", "Three"]
  let selectedOption = parameterOption.randomElement()
  return selectedOption!
}

print(genNumofParameters())

Note the ! after return selectedOption.

Here’s the article that I found: https://www.dev2qa.com/how-to-fix-error-value-of-optional-type-must-be-unwrapped-to-a-value-of-type-in-swift/

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.