Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 587 Vote(s) - 3.55 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What does an exclamation mark mean in the Swift language?

#21
Here is what I think is the difference:

var john: Person?
Means john can be nil

john?.apartment = number73
The compiler will interpret this line as:

if john != nil {
john.apartment = number73
}

While

john!.apartment = number73
The compiler will interpret this line as simply:

john.apartment = number73

Hence, using `!` will unwrap the if statement, and make it run faster, but if john is nil, then a runtime error will happen.

So wrap here doesn't mean it is memory wrapped, but it means it is code wrapped, in this case it is wrapped with an if statement, and because Apple pay close attention to performance in runtime, they want to give you a way to make your app run with the best possible performance.

**Update:**

Getting back to this answer after 4 years, as I got the highest reputations from it in Stackoverflow :)
I misunderstood a little the meaning of unwrapping at that time. Now after 4 years I believe the meaning of unwrapping here is to expand the code from its original compact form. Also it means removing the vagueness around that object, as we are not sure by definition if it is nil or not. Just like the [answer of Ashley above][1], think about it as a present which could contain nothing in it. But I still think that the unwrapping is code unwrapping and not memory based unwrapping as using enum.


[1]:

[To see links please register here]

Reply

#22
`john` is an optional `var` and it can contain a `nil` value. To ensure that the value isn't nil use a `!` at the end of the `var` name.

From documentation

**“Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.”**

Another way to check non nil value is (optional unwrapping)

if let j = json {
// do something with j
}
Reply

#23
**For Googlers:**

```lang-swift
john!.department
```

...tells compiler:

- I know `john` is optional
- Use it as if it has value
- Just crash if it does not

In production, use `guard let` or `if let` to deal with the situation of no-value and void hard crashes.
Reply

#24
Some big picture perspective to add to the other useful but more detail-centric answers:

In Swift, the exclamation point appears in several contexts:

- Forced unwrapping: `let name = nameLabel!.text`
- Implicitly unwrapped optionals: `var logo: UIImageView!`
- Forced casting: `logo.image = thing as! UIImage`
- Unhandled exceptions: `try! NSJSONSerialization.JSONObjectWithData(data, [])`

Every one of these is a different language construct with a different meaning, but they all have three important things in common:

### 1. Exclamation points circumvent Swift’s compile-time error handling checks.

When you use `!` in Swift, you are essentially saying, “Hey, compiler, I know you think an error _could_ happen here, but I _know_ with total certainty that it never will.”

(**Edit to clarify:** The force-unwrapping `!` is still “safe” in the language design sense that is it _not undefined behavior_, and is guaranteed to crash in a clean, predictable way (unlike dereferencing a null pointer in C or C++). It is not “safe” in the app developer sense that the language makes sure your app won’t suddenly fail because of your bad assumptions.)

Not all valid code fits into the box of Swift’s compile-time type system — or _any_ language’s static type checking, for that matter. There are situations where you can logically prove that an error will never happen, but you can’t prove it _to the compiler_. That’s why Swift’s designers added these features in the first place.

However, whenever you use `!`, you’re ruling out having a recovery path for an error, which means that…

### 2. Exclamation points are potential crashes.

An exclamation point also says, “Hey Swift, I am _so_ certain that this error can never happen that it’s better for you to _crash my whole app_ than it is for me to code a recovery path for it.”

That’s a dangerous assertion. It _can_ be the correct one: in mission-critical code where you have thought hard about your code’s invariants, it may be that bogus output is worse than a crash.

However, when I see `!` in the wild, it's rarely used so mindfully. Instead, it too often means, “this value was optional and I didn’t really think too hard about _why_ it could be nil or how to properly handle that situation, but adding `!` made it compile … so my code is correct, right?”

Beware the arrogance of the exclamation point. Instead…

### 3. Exclamation points are best used sparingly.

Every one of these `!` constructs has a `?` counterpart that forces you to deal with the error/nil case:

- Conditional unwrapping: `if let name = nameLabel?.text { ... }`
- Optionals: `var logo: UIImageView?`
- Conditional casts: `logo.image = thing as? UIImage`
- Nil-on-failure exceptions: `try? NSJSONSerialization.JSONObjectWithData(data, [])`

If you are tempted to use `!`, it is always good to consider carefully why you are not using `?` instead. Is crashing your program really the best option if the `!` operation fails? **Why is that value optional/failable?**

Is there a reasonable recovery path your code could take in the nil/error case? If so, code it.

If it can’t possibly be nil, if the error can never happen, then is there a reasonable way to rework your logic so that the compiler knows that? If so, do it; your code will be less error-prone.

There are times when there is no reasonable way to handle an error, and **ignoring the error — and thus proceeding with wrong data — would be _worse_ than crashing**. _Those_ are the times to use force unwrapping.

I periodically search my entire codebase for `!` and audit every use of it. Very few usages stand up to scrutiny. (As of this writing, the entire Siesta framework has exactly [two](

[To see links please register here]

) [instances](

[To see links please register here]

) of it.)

That’s not to say you should _never_ use `!` in your code — just that you should use it _mindfully_, and never make it the default option.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through