4

So I've recently been learning Swift (3.1), and I've had problems with understanding the purpose/practical usage of optionals.

I've researched several sites, and all they talk about is how to use them, not why or when they are used (Sort of why, but not in a way that seems applicable to me). My citations are at the end.

I understand about how its either nil or a value, and how you need to unwrap it's possible value with !, as well as how to create auto-unwrapping optionals.

My main question is just, what are the practical uses of optionals? Apple's Swift handbook said that optionals are the central point of most of Swift's most powerful features, so I feel like it is a concept very worthwhile to fully understand. I fully understand how to write them, I just can't grasp why or when you would use them.

Citations:

https://www.tutorialspoint.com/swift/swift_optionals.htm

http://blog.teamtreehouse.com/understanding-optionals-swift

Thank you for your time.

  • One typical way that I use `optional` is when at the time in `init`, the class doesn't know the value for a variable. And that is assigned anytime during the lifecycle of the object. – Shamas S Jun 01 '17 at 05:03

1 Answers1

3

As per my understanding : Swift is a safe bound checking language , so it implements it using variable checking whether they are nil or assigned value.

Optionals can be used when you don't know for sure before hand that we would have a value in a specific variable throughout the program.

So if you defined a Text Field & assigned its text to a variable. Maybe user just keeps it blank & you binded that text field's data to a variable. On runtime it would be empty , for reasons to avoid crash you could define an optional.

In the program when you would access optional value you have to make sure that the variable is present using "if let optional" or explicitly unwrapping the optionals. Explicitly unwrapping optionals are bad move & only should be done when you're sure there is a value present in that optional variable.

Swift uses optionals everywhere.

Disclosure : I'm still new to Swift & this would be first answer. Maybe my answer isn't well put to Stack Overflow's standards.

sensehack
  • 31
  • 4