-6

Good Morning everyBody,

I would like to ask why sometimes we put the Character "!" ?

and sometimes we put the Character "?" (like as?)

please explain me these.

  • 2
    take a look at **optionals** in swift, these are the concepts behind ! and ? in your code – nburk Apr 16 '15 at 08:18
  • possible duplicate of [What is an optional value in Swift?](http://stackoverflow.com/questions/24003642/what-is-an-optional-value-in-swift) – nburk Apr 16 '15 at 08:19
  • the `?` mark tells the computer the actual task is questionable, so if the computer is not in the mood in runtime, those lines can be ignored entirely; the `!` instructs the computer to do the task without questioning it. I guess. – holex Apr 16 '15 at 09:06

3 Answers3

2

"?" is called Optional and "!" is Implicitly Unwrapped Optionals. You can find more info here in Optionals and Implicit Unwrapped Optionals Section.

Some excerpt as follow:

Optionals (?): Swift introduces optional types, which handles absence of value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all.

Implicitly Unwrapped Optionals (!): Sometimes it is clear from a program’s structure that an optional will always have a value, after that value is first set. In these cases, it is useful to remove the need to check and unwrap the optional’s value every time it is accessed, because it can be safely assumed to have a value all of the time.

Vivek Molkar
  • 3,910
  • 1
  • 34
  • 46
0

As swift compiler is more strict in object use, you have to be put the optional object or non-optional object in your call. However, XCode has auto-complete feature for code editing so that the compiler validate your code.

Generally, XCode add ! to your variable when you pass an optional variable to a call that requires a non-optional variable. This case is dangerous cause if your object does not have value, application can be crashes. You should verify your self or you have to sure that your object contains value.

And, XCode add ? to your variable to give your optional variable a chance to unwrap and to be used if possible. Of course, the API in your call must accept an optional variable. Also, this is to try to cast your variable to the right format. Take a look at "Optional Chaining" document in Apple site here.

Vivek Molkar
  • 3,910
  • 1
  • 34
  • 46
Duyen-Hoa
  • 15,384
  • 5
  • 35
  • 44
0

To put it as simply as i can:

? means it`s optional. So the variable could be nil or its actual value

! means that this value should never be nil. And if for any reason this became nil the app should crash.

My advice is to never use "!" because you don`t want you are app to crash. Instead if you have an optional use the unwrapping method bellow:

var x:String? = nil

if let unwrapped_x = x {
    //x is not nil
}
else{
   //x is nil
}