-4

Consider the following statement

var aString: String! = "this is a test string"

Now as we see that aString always needs to hold a value "" or some text. Then what is the use of making it a implicit unwrapped optional. Why can't it be a simple String like :

var aString: String = "this is a test string"

Also I would like to understand the purpose of implicit unwrapped optionals existence other then in case of IBOutlets.

In other words what is the benefit of making a var implicit unwrapped optional when we know it always have some non nil value, why should not we declare it as a normal var.

Rizwan
  • 3,324
  • 3
  • 17
  • 38
  • 1
    Check out this answer: https://stackoverflow.com/a/38817733/7653367 – Jacob Ahlberg Oct 25 '18 at 11:09
  • 4
    Possible duplicate of [Difference between Force Unwrapping Optionals and Implicitly Unwrapped Optionals](https://stackoverflow.com/questions/38817494/difference-between-force-unwrapping-optionals-and-implicitly-unwrapped-optionals) – Dávid Pásztor Oct 25 '18 at 11:10
  • 1
    @JacobAhlberg,David - I have seen that answer, I understand diff between "Force Unwrapping Optionals and Implicitly Unwrapped Optionals". My question is on existence of Forced unwrapping options. – Rizwan Oct 25 '18 at 11:12
  • 1
    The first statement doesn't make sense at all. You could've asked this question in a much more better way. – Desdenova Oct 25 '18 at 11:27
  • "Its not what its why". You are asking that regarding to let aString: String! = "this is a test string"? This is the most stupid case to make it an optional, since there is no way it can ever ever ever be optional, since it is immutable. If you find any code that does that, report it to the police. – J. Doe Oct 25 '18 at 11:38
  • @J.Doe - consider that to be a var. – Rizwan Oct 25 '18 at 13:34
  • 2
    *I understand different types of option(al)s in swift*. No you don't. Implicit unwrapped optional is **not a type**. It's part of a declaration. Please read https://swift.org/blog/iuo/. Avoid IUO as much as possible. @DávidPásztor The linked question is outdated. IUO has a different meaning in Swift 4.2+ – vadian Oct 25 '18 at 13:41

1 Answers1

3

It's all related to the class initialization.

take Outlets for example they're force unwrapped because we know they will hold a value after initialization from the XIB or Storyboard but they will not be set before the class initialization.

A force unwrapped optional exits to tell the compiler I'm taking the responsibility to make sure this variable will be set before calling it.

in your example I don't think it makes sense to write:

let aString: String! = "this is a test string"

It should just be as you wrote:

let aString: String = "this is a test string"

It makes more sense to have:

var aString: String!

meaning you'll take ownership of this variable initialization (i.e making sure it's not nil)

ahbou
  • 4,710
  • 23
  • 36