-2

When read a Swift project I could not understand the following code:

self.myTabbar?.addSubview(button)

In my opinion ,It should looks like this:

self.myTabbar!.addSubview(button)

Why it is correct to use ?

PravinS
  • 2,640
  • 3
  • 21
  • 25
  • 5
    Please have a look at the SWIFT documentation https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html – AlexWoe89 Jan 22 '16 at 12:15
  • Possible duplicate of [What is the difference between String? and String! (Two ways of creating an optional variable)?](http://stackoverflow.com/questions/24083842/what-is-the-difference-between-string-and-string-two-ways-of-creating-an-opti) – NSNoob Jan 22 '16 at 12:17
  • Possible duplicate of [What does an exclamation mark mean in the Swift language?](http://stackoverflow.com/questions/24018327/what-does-an-exclamation-mark-mean-in-the-swift-language) – Eric Aya Jan 22 '16 at 12:33

1 Answers1

1

When you use ! you must be sure that the variable is not nil, otherwise it crashes. In this case is correct to use ? because the addSubview method call it's executed only if the variable is not nil, in case it is nil it just skips that line.

Massimo Frasson
  • 427
  • 3
  • 10