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? ) value can be changed and do not need to be initialized. The swift variable and constant must has an initialized value before use it, otherwise the compiler will throw error message like Variable ‘x’ used before being initialized. The optional variable do not need to have initial value then you can use it, but if you do not assign initial value, the optional variable’s value is nil.

1. Difference Between Variable, Constant & Optional Variable.

  1. Variable & constant must be assigned value before use 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)

    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 variable do not need initial value, but if not being assigned value, the optional variable’s value is nil. Below code will not throw 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 of no value has been assigned to x.

    nil

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

    var x:Int? = 10
    
    print(x)

    Above code will get below result.

    Optional(10)

2. How To Unwrap Optional Variable Value In Swift.

From section one, we have know what is swift optional variable. Optional variable make code more safe if you forget give initial value to a variable. Optional variable can have a value or be nil if have no value.

READ :   How To Set Application Root View Controller Programmatically In Xcode 11

But in real programming, we need to get the original value that is wrapped by the optional variable. Otherwise you may encounter 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 optional variable’s value.

2.1 Force Unwrap 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 above code will get 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 ! 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 which do not has value that means the variable value is nil, if you use force unwrap in this case, you will encounter 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 above code will result in below error message.

Fatal error: Unexpectedly found nil while unwrapping an Optional value

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

If you really want to force unwrap an optional variable that is nil, you need use 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")
}

Above code will print below result, because x do not has initial value so it is nil.

x is nil

But if you have many optional variables, you need a lot of if condition 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.

READ :   How To Use iOS UISegmentedControl In Swift Programmatically Example
2.2.1 Combine Multiple if let Statements In Optional Binding.

If you have multiple optional variable, 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 above code will get below result.

Salary is 10000.0

2.3 Use Optional Chaining To Unwrap Value.

If you have multiple optional variables which has relations such as 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)

}

Leave a Reply

Your email address will not be published. Required fields are marked *

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