How To Fix Error ‘Value Of Optional Type Must Be Unwrapped To A Value Of Type’ In Swift

There are three kinds of variable declaration in swift programming. You can declare a swift variable as a variable (var name: String = "jerry ") that value can be changed in code, a constant ( let x:Int = Int(10) ) that value can not be changed, and an optional variable ( var x:Int? ) that value can be changed and does not need to be initialized.

The swift variable and constant must have an initialized value before using it, otherwise, the compiler will throw an error message like Variable ‘x’ used before being initialized. The optional variable does not need to have an initial value then you can use it, but if you do not assign an initial value, the optional variable’s value is nil.

1. Difference Between Variable, Constant & Optional Variable.

  1. Variable & constant must be assigned value before using it, otherwise, an error will be thrown.
    // Declare an Int variable without initial value.
    var x:Int
    
    // Below code will throw error : variable 'x' used before being initialized.
    print(x)

    The below code is correct usage.

    // Declare variable and assign an initial value.
    var x:Int = 10
    
    // Below code will print 10 in the console.
    print(x)
  2. Optional variables do not need initial value, but if not being assigned value, the optional variable’s value is nil. The below code will not throw an error.
    // Declare an optional variable with a question mark (?) at the end of the variable type.
    var x:Int?
    
    print(x)
    

    Below is the output value nil because no value has been assigned to x.

    nil

    But if you give an optional variable x an initial value, the output will be Optional(10) like below. So if you want to get the original value of 10, you need to unwrap the optional variable, we will discuss it later.

    var x:Int? = 10
    
    print(x)

    The above code will get the below result.

    Optional(10)

2. How To Unwrap Optional Variable Value In Swift.

From section one, we have learned what is a swift optional variable. Swift optional variables make code safer if you forget to give an initial value to a variable. The swift optional variable can have a value or be nil if have no value.

But in real programming, we need to get the original value that is wrapped by the optional variable. Otherwise, you may encounter an error message like Value of optional type ‘Dictionary<String, String>.Index?’ must be unwrapped to a value of type ‘Dictionary<String, String>.Index’. Now let me show you how to unwrap the optional variable’s value.

2.1 Force Unwrap Swift Optional Variable Value.

This is the easy and straightforward method to unwrap an optional variable value. Just add ! at the end of the optional variable to unwrap it to get the original value.

var x:Int? = 10

print(x!)

Run the above code will get the below result.

10

So to resolve error Value of optional type ‘Dictionary<String, String>.Index?’ must be unwrapped to a value of type ‘Dictionary<String, String>.Index’, you need to add the character ! at the end of the variable to unwrap optional type ‘Dictionary<String, String>.Index?’ to ‘Dictionary<String, String>.Index’.

2.2 Unwrap Optional Variable Use Optional Binding.

When you want to unwrap an optional variable that does not has a value that means the variable value is nil, if you use force unwrap in this case, you will encounter an error like below.

// Declare an optional variable, the variable do not has value then it's value is nil.
var x:Int? 

print(x!)

Execute the above code will result in the below error message.

Fatal error: Unexpectedly found nil while unwrapping an Optional value

So, for the nil value optional variable, you can not use the force unwrap method.

If you really want to force unwrap an optional variable that is nil, you need to use the if condition to check whether the optional variable is nil or not.

var x:Int?

if(x != nil){
    print(x!)
}else{
    print("x is nil")
}

The above code will print the below result because x does not has an initial value so it is nil.

x is nil

But if you have many optional variables, you need a lot of if conditions to check, this is very tedious. But you can use optional binding to resolve this error like below.

// Define an optional variable without assign value, so it's value is nil.
var x:Int?

// Optional binding x value to y use let variable_2 = variable_1, it will assign value to y only when x is not nil. Because x is nil now, so the print(y) will not be executed.
if let y = x{
    print(y)
}

// Assign 100 to x.
x = 100

// Optional binding x's value to y again, now x is not nil, so y has value and the condition body will be executed.
if let y = x{
    print(y)
}

So the optional binding format is if let var_2 = var_1 if var_1 is not nil, then the if condition body will be executed.

2.2.1 Combine Multiple if let Statements In Optional Binding.

If you have multiple optional variables, you can combine multiple if let statements in optional binding like below.

if  let user_name = usernameField.text,
    let password = passwordField.text
{
    // login user account
}
2.2.2 Use Optional Binding For Function Result.
if let salary = Double("10000")
{
    print("Salary is \(salary)")
}

Execute the above code will get the below result.

Salary is 10000.0

2.3 Use Optional Chaining To Unwrap Value.

If you have multiple optional variables which have relations such as the outlet of a UI component, you can use optional chaining to make your code simple like below. In optional chaining, each optional variable ends with a question mark (?) without white space.

if let text = a?.b?.c?.text {

   print(text)

}
0 0 vote
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
burke
burke

I want to learn iOS progrmming, and I want to use swift programming language. But when I link the view component and the controller use actions or outlets, when I reference the view component in the source code, I always meet error message like Value of optional type ‘String?’ must be unwrapped to a value of type ‘String’ , Force-unwrap using ‘!’ to abort execution if the optional value contains ‘nil’.

I read this article and has some concepts about swift optional variables, but I do not know why it shows such errors in my application. How can I fix this?

2
0
Would love your thoughts, please comment.x
()
x