-2

I was just wondering what is the difference between "?" and "!" in swift, I'm new to swift. I tried looking for questions similar in here, but couldn't find any.

  • 3
    See the discussion on Optionals here: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html – Mike Taverne Apr 24 '18 at 01:48
  • 3
    Possible duplicate of [Difference between optional and forced unwrapping](https://stackoverflow.com/questions/28665375/difference-between-optional-and-forced-unwrapping) – Jaydeep Vora Apr 24 '18 at 03:33
  • Also on topic : https://stackoverflow.com/questions/24003642/what-is-an-optional-value-in-swift – Dan Beaulieu Apr 24 '18 at 04:39
  • Why same question again there are already many answers for this. – TheTiger Apr 24 '18 at 04:49
  • Possible duplicate of [What is an optional value in Swift?](https://stackoverflow.com/questions/24003642/what-is-an-optional-value-in-swift) – NobodyNada Apr 29 '18 at 21:56

3 Answers3

3

An optional type can be nil

var nameOfToy: String?

The toy may have a name;

nameOfToy = "Buzz"

so

print (nameOfToy!)

is Buzz.

The question mark indicates that it is optional, i.e. can be nil, so you have to UNWRAP it with the !. This is because the variable is optional.

But what happens if there is no name of a toy, and you use !. In this case you get a nasty crash.

stevenpcurtis
  • 1,907
  • 3
  • 21
  • 47
  • Thank you so much! my god it makes soooooooooooooo much sense now. – Ibrahim Ayyoub Apr 24 '18 at 01:53
  • There are so many other uses of `?` (`as?`, `try?`, optional chaining with `?.`, optional subscripting, optional calling `?()`), and all the `!` variants of those, that aren't covered in this answer. It's also missing any mention of implicitly unwrapped optionals, which makes it seem very incomplete. – Alexander Apr 24 '18 at 03:40
  • Mike Taverne linked to https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html so you might want to look there for an answer that covers everything in your judgement, or you might (you know), write your own answer Alex. – stevenpcurtis Apr 24 '18 at 03:48
  • @IbrahimAyyoub but don't use the `!` to unwrap your optional values unless your program can go no further without the value you are attempting to unwrap. Doing so is bad practice. Instead of using `!` to unwrap, you should nearly always safely unwrap your optional values using `if-let` or `guard`. – Dan Beaulieu Apr 24 '18 at 04:37
2

These characters have different meanings depending on the context. More than likely you are referring to their uses in unwrapping optionals.

If you have a variable foo:

var foo: Int?

You have declared the variable as an Optional. An Optional is a variable that can contain some value, or no value (nil.) Think of an Optional as a box, or wrapper, around another data type. In order to get at the value inside the optional, you have to unwrap it.

The question mark is the unwrap operator.

Say you have a more complex object like a struct:

struct Foo {
  bar: Int
}

var aFoo: Foo?

You've created an Optional instance of Foo called aFoo. The variable aFoo either contains a Foo object, or it contains nil.

You could use code like this:

if aFoo?.bar == 3 {
   print("aFoo contains an int == 3")
} else {
   print("aFoo is either nil or contains some other value")
}

The ! operator is the "force unwrap" operator. I call it the "crash if nil" operator. If you rewrite the code above using force-unwap:

if aFoo!.bar == 3 {
   print("aFoo contains an int == 3")
}

Then there is no point in having an else clause, since if aFoo is nil, you are guaranteed to crash.

You should only use the force-unwrap operator if you are certain that the Optional is not nil.

Optionals are a very important concept in Swift, so you should study them, and the various ways to handle them, until it's second nature.

Make sure you learn about "optional chaining", "optional binding", the nil coalescing operator, guard statements, and force unwrapping, to name a few techniques to deal with optionals.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Thanks this was just a longer example, but I get it now thank you so much. – Ibrahim Ayyoub Apr 24 '18 at 01:53
  • Again, it's a fairly complex subject that's CENTRAL to mastering Swift. It's unlikely you fully get it after reading a couple of SO posts. Make sure you invest enough time to learn about the various things I mentioned in my answer. – Duncan C Apr 24 '18 at 14:27
0

“To declare an optional, we just have to add a question mark after the type’s name.To read the value of an optional, we have to unwrap it by adding an exclamation mark at the end of the name.”

“Declaring implicitly unwrapped optionals”

“Swift provides the possibility to declare implicitly unwrapped optionals. These are optional variables declared with the exclamation mark instead of the question mark. The system reads these variables as optionals until they are assigned a value and therefore we don’t have to unwrap them anymore.”

var mynumber: Int!
mynumber = 5
var total = mynumber * 10  // 50
Mario Burga
  • 1,107
  • 1
  • 13
  • 19