Understanding optional unwrapping and force unwarpping

optional
(Arka Sadhu) #1

Hi. I am new to swift and am having some trouble understanding optionals.

From what I understand Optional types are used when something may not have a designated value. However, many operations require the value to be non-optional which requires unwrapping.

Most sources I have come across say we need ! after the variable name to unwrap it. However, if the value is indeed nil then it would throw an error. This is why it is discouraged to use this approach (to the best of my understanding).

The other way is to do optional unwrapping. However, I am unable to get this part correctly, because at the end I am still having to do the unwrapping via !.

As an example suppose I have the following:

let nums : [Int] = [1, 2, 3, 5]
let nums_dct : [Int : Int] = [0:1, 1: 2, 2: 3, 3: 5]
nums[nums_dct[0]] // throws an error
nums[nums_dct[0]!] //doesn't throw an error

The error is due to nums_dct[0] giving Int? output. What is an elegant way to do the above without using !

Thanks

(David Smith) #2

The key thing here is to decide what you want to happen if there isn't a value. Here's some possibilities:

  • Perhaps you know (as is true in your example code) that in practice it's never going to be nil. If so, using ! is fine
  • Perhaps you don't have any reasonable thing you can do if the thing is nil, and it's just an error if it happens. If so, ! is also probably fine, since it will crash and report an error, rather than doing something unexpected.
  • Perhaps you have a specific value you can use if it's nil; in that case you can use ?? to provide a default value, like this: nums[nums_dct[0] ?? 0]
  • Perhaps you want to do something else if it's nil; in that case you can use guard let index = nums_dct[0] else { do something else then return } or if let index = nums_dct[0] { nums[index] } else { do something else }
3 Likes
(Alexander Momchilov) #3

You would really benefit from reading through the Swift language guide. Most of what you're asking about is covered in the first section, titled The Basics, and the rest is covered in Control Flow and Optional Chaining.

1 Like
(Arka Sadhu) #4

@David_Smith thank you for the detailed answer. It clarified a few misconceptions I had.

@AlexanderM thank you for the link. I was following the language guide, but I was unable to understand the optional chaining very well. I will look into it once again.

(Alexander Momchilov) #5

You should mention that in your post! People are much more eager to help those who have shown due diligence.

Let me know if you have questions regarding that guide, I'd be happy to answer!

(发抖喵小咪) #6

Optional chains are just a hard reminder to deal with situations where objects may be empty. I think it's his main role. If you use ! to unpack, it's the same as OC.That would be unsafe.