By Troy


2014-06-03 14:52:26 8 Comments

The Swift Programming Language guide has the following example:

class Person {
    let name: String
    init(name: String) { self.name = name }
    var apartment: Apartment?
    deinit { println("\(name) is being deinitialized") }
}

class Apartment {
    let number: Int
    init(number: Int) { self.number = number }
    var tenant: Person?
    deinit { println("Apartment #\(number) is being deinitialized") }
}

var john: Person?
var number73: Apartment?

john = Person(name: "John Appleseed")
number73 = Apartment(number: 73)

//From Apple's “The Swift Programming Language” guide (https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html)

Then when assigning the apartment to the person, they use an exclamation point to "unwrap the instance":

john!.apartment = number73

What does it mean to "unwrap the instance"? Why is it necessary? How is it different from just doing the following:

john.apartment = number73

I'm very new to the Swift language. Just trying to get the basics down.


UPDATE:
The big piece of the puzzle that I was missing (not directly stated in the answers - at least not at the time of writing this) is that when you do the following:

var john: Person?

that does NOT mean that "john is of type Person and it might be nil", as I originally thought. I was simply misunderstanding that Person and Person? are completely separate types. Once I grasped that, all of the other ?, ! madness, and the great answers below, made a lot more sense.

22 comments

@Paul Cantrell 2015-10-28 19:30:55

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 safety 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.”

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 simply 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 instances 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.

@jenson-button-event 2016-03-09 09:08:34

func isSubscriptionActive(receiptData: NSDictionary?) -> Bool { if(receiptData == nil) { return false; } return (hasValidTrial(receiptData!) || isNotExpired(receiptData!)) && isNotCancelled(receiptData!) } Given 3. is there a better way to write it?

@rkgibson2 2017-01-30 23:01:17

You can say func isSubscriptionActive(receiptData: NSDictionary?) -> Bool { guard let nonNilReceiptData = receiptData else { return false} return (hasValidTrial(nonNilReceiptData) || isNotExpired(nonNilReceiptData)) && isNotCancelled(nonNilReceiptData) }

@gnasher729 2018-01-11 20:00:28

Exclamation marks don't circumvent any safety checks. You get a guaranteed crash if the optional is nil. The optional is always checked. It's just a very brutal way to make a safety check.

@Paul Cantrell 2018-01-12 01:21:53

@gnasher729 As the answer states, it circumvents the compile-time safety checks in favor of a safe runtime failure.

@Amr 2014-06-20 04:16:44

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 of it is nil or not. Just like the answer of Ashley above, 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.

@Chuck Pinkert 2015-02-24 18:38:26

In my playground john.apartment = number73 does not compile, you must specify john?.apartment = number73

@Bruce 2015-06-06 08:08:43

@ChuckPinkert is right, the 4th line should be edited to john?.apartment = number73, nice answer though!

@spiderman 2015-06-26 08:10:06

john.apartment = number73 gives error: value of Optional type 'Person?' not unwrapped: did you mean to use '!' or '?'?

@madidier 2016-06-07 19:54:21

The unwrapping has nothing to do w.r.t performance. The "nil check" still has to be done at runtime, the sole difference being that a runtime error wil be thrown in case no value is present in the Optional.

@Honey 2016-08-08 13:30:17

ASK YOURSELF

  • Does the type person? have an apartment member/property? OR
  • Does the type person have an apartment member/property?

If you can't answer this question, then continue reading:

To understand you may need super-basic level of understanding of Generics. See here. A lot of things in Swift are written using Generics. Optionals included

The code below has been made available from this Stanford video. Highly recommend you to watch the first 5 minutes

An Optional is an enum with only 2 cases

enum Optional<T>{
    case None
    case Some(T)
}

let x: String? = nil //actually means:

let x = Optional<String>.None

let x :String? = "hello" //actually means:

let x = Optional<String>.Some("hello")

var y = x! // actually means:

switch x {
case .Some(let value): y = value
case .None: // Raise an exception
}

Optional binding:

let x:String? = something
if let y = x {
    // do something with y
}
//Actually means:

switch x{
case .Some(let y): print)(y) // or whatever else you like using 
case .None: break
}

when you say var john: Person? You actually mean such:

enum Optional<Person>{
case .None
case .Some(Person)
}

Does the above enum have any property named apartment? Do you see it anywhere? It's not there at all! However if you unwrap it ie do person! then you can ... what it does under the hood is : Optional<Person>.Some(Person(name: "John Appleseed"))


Had you defined var john: Person instead of: var john: Person? then you would have no longer needed to have the ! used, because Person itself does have a member of apartment


As a future discussion on why using ! to unwrap is sometimes not recommended see this Q&A

@dfri 2016-08-08 13:36:39

Using the actual slides above is possibly copyright infringement: "... Stanford University does retain copyright to all content in our iTunes U collection.", from http://itunes.stanford.edu. Probably better to answer, in you own words, the content you learned from the course that you perceive to answer this question (and instead of using the slides, rather quote relevant parts of them in code form, with references, naturally).

@Honey 2016-08-08 13:52:20

@dfri Stanford itself has shared their slides on iTunes U for free. I have seen their slides on multiple answers and their slides being shared on internet freely. I have seen many times people copy/paste from blogs and attributing to them. This is possibly the first time I am seeing someone countering the approach. I have also attributed to them. Anyhow, thanks for your concern.

@dfri 2016-08-08 14:01:02

Your argument is argumentum ad populum. Anyway, I don't believe Stanford will come here and enforce DMCA rights, but its always better if your answers are in your own words based on official/valid sources, and not in the form of copying those sources outright as above; especially when we talk about copyrighted slides: again, better to quote the content of the slides in code blocks (images of code is generally a no-no here at SO!).

@Honey 2016-08-08 14:15:28

From the link you sent: "From a copyright perspective, I don't think that's true. Instead, they have to remove infringing content as soon as the copyright owner requests it. The difference is that some owners encourage the spread of their content in this manner, often in the simple hope of gaining notoriety."---I don't mean to say you're wrong rather I really don't know if what I am doing is correct or what you are saying is correct.

@dfri 2016-08-08 14:24:02

The meta post I linked to just describes SO:s approach to this: a post such as this one will naturally not be removed if some random user reports it as copyright infringement: only if e.g. a Stanford rep. were to come here and as the post to be removed would SO need to enforce it. Hence I wrote "I don't believe Stanford will come here and enforce DMCA rights, ...". My point above is that I believe this to be possibly copyright infringement (which I believe to be wrong), but naturally no one will ever enforce this. ...

@Honey 2016-08-08 14:25:44

Awesome, thanks for your consideration. Let's enjoy SO and iTunes U

@dfri 2016-08-08 14:26:21

But this aside, posting questions or answers which contain images of code is upright discouraged for a number of reasons. To wrap it up: I've tried to point out with these comments that I believe this answer, in its current form, is not entirely as good as it could be, due to two major reasons (copyrighted slides, image of code). Naturally no one, including myself, will do anything about this, I'm simply pointing it our for future reference (or possibly encouraging you to edit this post with quote by code blocks instead). Agreed, iTunes U! :)

@Honey 2017-01-25 19:13:17

@dfri removed images

@jeff ayan 2016-10-25 04:58:57

Simple the Optional variable allows nil to be stored.

var str : String? = nil

str = "Data"

To convert Optional to the Specific DataType, We unwrap the variable using the keyword "!"

func get(message : String){
   return
}

get(message : str!)  // Unwapped to pass as String

@Dalija Prasnikar 2016-10-25 11:11:40

Please don't write answers that are not adding anything that has not already been covered by previous answers.

@Ashish Pisey 2017-09-06 13:47:38

An Optional variable may contain a value or may be not

case 1: var myVar:String? = "Something"

case 2: var myVar:String? = nil

now if you ask myVar!, you are telling compiler to return a value in case 1 it will return "Something"

in case 2 it will crash.

Meaning ! mark will force compiler to return a value, even if its not there. thats why the name Force Unwrapping.

@Ashish Pisey 2017-09-14 03:52:01

@Moritz. I dont know is it so ? Cant i answer if a question is already answered? Am i causing any problem or is there anything wrong in my answer ? i dont understand Why are you downvoting it for answering it correctly? I tried to answer based on my understanding of the concept. i think some people will find it helpful for clear and easy explanation.

@Ashish Pisey 2017-09-18 04:30:32

@Moritz Now this is constructive. You should have told me this correction in the first place, if this was the reason. thanks for the feedback. i have corrected it.

@Andy Lebowitz 2017-08-14 03:13:12

If you use it as an optional, it unwraps the optional and sees if something is there. If you use it in an if-else statement is is code for NOT. For example,

if (myNumber != 3){
 // if myNumber is NOT 3 do whatever is inside these brackets.
)

@Ramkumar chintala 2015-07-10 08:32:27

Here are some examples:

var name:String = "Hello World"
var word:String?

Where word is an optional value. means it may or may not contain a value.

word = name 

Here name has a value so we can assign it

var cow:String = nil
var dog:String!

Where dog is forcefully unwrapped means it must contain a value

dog = cow

The application will crash because we are assign nil to unwrapped

@Asususer 2017-08-01 02:29:44

var c:Int = nil will get: "Nil cannot initialize specified type 'int'"

@Ramkumar chintala 2017-08-01 07:26:34

@Asususer updated answer check once

@Alex Nolasco 2014-07-17 02:22:28

TL;DR

What does an exclamation mark mean in the Swift language?

The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.” This is known as forced unwrapping of the optional’s value:

Example

let possibleString: String? = "An optional string."
print(possibleString!) // requires an exclamation mark to access its value
// prints "An optional string."

let assumedString: String! = "An implicitly unwrapped optional string."
print(assumedString)  // no exclamation mark is needed to access its value
// prints "An implicitly unwrapped optional string."

Source: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_399

@NSP 2014-11-28 12:44:07

I come to know that "?" and "!" is used to handle optional string but difference between them is explained by your answer. Thanks :)

@pachun 2015-08-10 06:37:23

Your answer is great because I understand what is going on now. What I don't understand is why implicitly unwrapped optionals exist. Why create something defined as an implicitly unwrapped optional String, rather than a regular String type? Their usage thereafter is the same. What am I missing?

@Fry 2014-06-03 14:54:39

john is an optional var. So can be contains 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

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

@Troy 2014-06-03 14:56:01

Yes, I had seen that in the documentation, but it still seems unnecessary... as, to me, john.apartment = number73 also says "I know that this optional definitely has a value; please use it."...

@lassej 2014-06-03 15:03:06

Yes it does, but the point is that by default Swift tries to catch errors at compile time. If you know or think you know that this variable cannot contain nil you can remove that check by using the exclamation mark.

@vishal dharankar 2017-01-19 11:02:42

The entire story begins with a feature of swift called optional vars. These are the vars which may have a value or may not have a value. In general swift doesn't allow us to use a variable which isn't initialised, as this may lead to crashes or unexpected reasons and also server a placeholder for backdoors. Thus in order to declare a variable whose value isn't initially determined we use a '?'. When such a variable is declared, to use it as a part of some expression one has to unwrap them before use, unwrapping is an operation through which value of a variable is discovered this applies to objects. Without unwrapping if you try to use them you will have compile time error. To unwrap a variable which is an optional var, exclamation mark "!" is used.

Now there are times when you know that such optional variables will be assigned values by system for example or your own program but sometime later , for example UI outlets, in such situation instead of declaring an optional variable using a question mark "?" we use "!".

Thus system knows that this variable which is declared with "!" is optional right now and has no value but will receive a value in later in its lifetime.

Thus exclamation mark holds two different usages, 1. To declare a variable which will be optional and will receive value definitely later 2. To unwrap an optional variable before using it in an expression.

Above descriptions avoids too much of technical stuff, i hope.

@Maninderjit Singh 2016-05-23 13:03:00

IN SIMPLE WORDS

USING Exclamation mark indicates that variable must consists non nil value (it never be nil)

@Jim Driscoll 2016-02-19 10:52:24

If you've come from a C-family language, you will be thinking "pointer to object of type X which might be the memory address 0 (NULL)", and if you're coming from a dynamically typed language you'll be thinking "Object which is probably of type X but might be of type undefined". Neither of these is actually correct, although in a roundabout way the first one is close.

The way you should be thinking of it is as if it's an object like:

struct Optional<T> {
   var isNil:Boolean
   var realObject:T
}

When you're testing your optional value with foo == nil it's really returning foo.isNil, and when you say foo! it's returning foo.realObject with an assertion that foo.isNil == false. It's important to note this because if foo actually is nil when you do foo!, that's a runtime error, so typically you'd want to use a conditional let instead unless you are very sure that the value will not be nil. This kind of trickery means that the language can be strongly typed without forcing you to test if values are nil everywhere.

In practice, it doesn't truly behave like that because the work is done by the compiler. At a high level there is a type Foo? which is separate to Foo, and that prevents funcs which accept type Foo from receiving a nil value, but at a low level an optional value isn't a true object because it has no properties or methods; it's likely that in fact it is a pointer which may by NULL(0) with the appropriate test when force-unwrapping.

There other situation in which you'd see an exclamation mark is on a type, as in:

func foo(bar: String!) {
    print(bar)
}

This is roughly equivalent to accepting an optional with a forced unwrap, i.e.:

func foo(bar: String?) {
    print(bar!)
}

You can use this to have a method which technically accepts an optional value but will have a runtime error if it is nil. In the current version of Swift this apparently bypasses the is-not-nil assertion so you'll have a low-level error instead. Generally not a good idea, but it can be useful when converting code from another language.

@En Hui Lim 2016-01-07 07:53:49

In Short (!): After you have declare a variable and that you are certain the variable is holding a value.

let assumedString: String! = "Some message..."
let implicitString: String = assumedString

else you would have to do this on every after passing value...

let possibleString: String? = "An optional string."
let forcedString: String = possibleString! // requires an exclamation mark

@Abdurrahman 2015-10-20 14:23:42

If you're familiar with C#, this is like Nullable types which are also declared using a question mark:

Person? thisPerson;

And the exclamation mark in this case is equivalent to accessing the .Value property of the nullable type like this:

thisPerson.Value

@cheborneck 2015-06-09 06:09:20

The ! at the end of an object says the object is an optional and to unwrap if it can otherwise returns a nil. This is often used to trap errors that would otherwise crash the program.

@brimstone 2015-02-26 18:25:25

To put it simply, exclamation marks mean an optional is being unwrapped. An optional is a variable that can have a value or not -- so you can check if the variable is empty, using an if let statement as shown here, and then force unwrap it. If you force unwrap an optional that is empty though, your program will crash, so be careful! Optionals are declared by putting a question mark at the end of an explicit assignment to a variable, for example I could write:

var optionalExample: String?

This variable has no value. If I were to unwrap it, the program would crash and Xcode would tell you you tried to unwrap an optional with a value of nil.

Hope that helped.

@Henry oscannlain-miller 2014-11-16 02:30:05

The ! means that you are force unwrapping the object the ! follows. More info can be found in Apples documentation, which can be found here: https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/TheBasics.html

@guest 2014-07-24 21:50:01

In this case...

var John: Person!

it means, that initially John will have nil value, it will be set and once set will never be nil-led again. Therefore for convenience I can use the easier syntax for accessing an optional var because this is an "Implicitly unwrapped optional"

@Kaydell 2014-09-06 00:13:48

Thank you. I'd also found the following link that explains this. This kind of type is called an "implicitly unwrapped option". stackoverflow.com/questions/24122601/…

@Ashley 2014-06-03 17:04:07

What does it mean to "unwrap the instance"? Why is it necessary?

As far as I can work out (this is very new to me, too)...

The term "wrapped" implies we should think of an Optional variable as a present, wrapped in shiny paper, which might (sadly!) be empty.

When "wrapped", the value of an Optional variable is an enum with two possible values (a little like a Boolean). This enum describes whether the variable holds a value (Some(T)), or not (None).

If there is a value, this can be obtained by "unwrapping" the variable (obtaining the T from Some(T)).

How is john!.apartment = number73 different from john.apartment = number73? (Paraphrased)

If you write the name of an Optional variable (eg text john, without the !), this refers to the "wrapped" enum (Some/None), not the value itself (T). So john isn't an instance of Person, and it doesn't have an apartment member:

john.apartment
// 'Person?' does not have a member named 'apartment'

The actual Person value can be unwrapped in various ways:

  • "forced unwrapping": john! (gives the Person value if it exists, runtime error if it is nil)
  • "optional binding": if let p = john { println(p) } (executes the println if the value exists)
  • "optional chaining": john?.learnAboutSwift() (executes this made-up method if the value exists)

I guess you choose one of these ways to unwrap, depending upon what should happen in the nil case, and how likely that is. This language design forces the nil case to be handled explicitly, which I suppose improves safety over Obj-C (where it is easy to forget to handle the nil case).

Update:

The exclamation mark is also used in the syntax for declaring "Implicitly Unwrapped Optionals".

In the examples so far, the john variable has been declared as var john:Person?, and it is an Optional. If you want the actual value of that variable, you must unwrap it, using one of the three methods above.

If it were declared as var john:Person! instead, the variable would be an Implicitly Unwrapped Optional (see the section with this heading in Apple's book). There is no need to unwrap this kind of variable when accessing the value, and john can be used without additional syntax. But Apple's book says:

Implicitly unwrapped optionals should not be used when there is a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable.

Update 2:

The article "Interesting Swift Features" by Mike Ash gives some motivation for optional types. I think it is great, clear writing.

Update 3:

Another useful article about the implicitly unwrapped optional use for the exclamation mark: "Swift and the Last Mile" by Chris Adamson. The article explains that this is a pragmatic measure by Apple used to declare the types used by their Objective-C frameworks which might contain nil. Declaring a type as optional (using ?) or implicitly unwrapped (using !) is "a tradeoff between safety and convenience". In the examples given in the article, Apple have chosen to declare the types as implicitly unwrapped, making the calling code more convenient, but less safe.

Perhaps Apple might comb through their frameworks in the future, removing the uncertainty of implicitly unwrapped ("probably never nil") parameters and replacing them with optional ("certainly could be nil in particular [hopefully, documented!] circumstances") or standard non-optional ("is never nil") declarations, based on the exact behaviour of their Objective-C code.

@Richard Washington 2014-06-07 00:05:50

I'm not sure about this explanation. If you just run the code without the ! it still returns the actual value. Maybe the ! is for speed?

@Richard Washington 2014-06-07 00:24:27

OK. So the docs talk about using ! when you know for sure it can be unwrapped. But you can run the code fine without it (a forth option for your list - implicit unwrapping) AND without checking first. You get back the value or nil if nil. But if you know for sure that it is not nil then use !......but I still can't see why you would do this?

@Ashley 2014-06-09 14:14:28

Hi @RichardWashington - I've added an update to my answer which hopefully clarifies some of this.

@Golden Thumb 2014-07-16 13:43:11

Update 3 is exactly what I'm looking for. Before reading it I thought Apple was lying when they returned something like NSURLCredential! which actually could be nil.

@Mihir 2014-07-23 21:34:31

Thanks for the fantastic answer @Ashley. After reading this answer and some of Apple's example swift code, it really seems to me that in this tradeoff between safety and productivity, usually it's best to be on the safer side. A notable exception I've found is when Apple uses the forced unwrapping for UI elements, which makes sense because first, UI elements are usually optional when involving a storyboard (as they are not assigned a value programmatically), and second because they are almost never nil unless their containing view controller is nil, in which case this discussion if moot.

@moonman239 2015-04-22 03:21:49

Here's another way to think about it: Let's say Amy wants to confirm that she has John's number in her phone. To do this, she looks up John's name in the phone book. If it's not there, she can do one of two things: she can assume the number she has is different from John's number, or she can go into a panic because she KNEW John was in the phonebook.

@Dominic 2015-09-07 10:52:38

It seems like the ! is pointless unless it's used on a ? declared var, I think they could have made things simpler by not requiring an optional var to be declared with ! and just make it implicit like every other language

@Gokul 2014-06-19 06:59:29

In objective C variables with no value were equal to 'nil'(it was also possible to use 'nil' values same as 0 and false), hence it was possible to use variables in conditional statements (Variables having values are same as 'TRUE' and those with no values were equal to 'FALSE').

Swift provides type safety by providing 'optional value'. i.e. It prevents errors formed from assigning variables of different types.

So in Swift, only booleans can be provided on conditional statements.

var hw = "Hello World"

Here, even-though 'hw' is a string, it can't be used in an if statement like in objective C.

//This is an error

if hw

 {..}

For that it needs to be created as,

var nhw : String? = "Hello World"

//This is correct

if nhw

 {..}

@Connor 2014-06-03 14:56:43

John is an optional Person, meaning it can hold a value or be nil.

john.apartment = number73

is used if john is not an optional. Since john is never nil we can be sure it won't call apartment on a nil value. While

john!.apartment = number73

promises the compiler that john is not nil then unwraps the optional to get john's value and accesses john's apartment property. Use this if you know that john is not nil. If you call this on a nil optional, you'll get a runtime error.

The documentation includes a nice example for using this where convertedNumber is an optional.

if convertedNumber {
    println("\(possibleNumber) has an integer value of \(convertedNumber!)")
} else {
    println("\(possibleNumber) could not be converted to an integer")
}

@Troy 2014-06-03 15:03:46

Are you saying that if john is nil, and I go john.apartment = number73, that WON'T result in an error unless I put a '!' after john?

@Connor 2014-06-03 15:07:58

If john is an optional you must use the exclamation point to access its properties because the compiler must know that it isn't nil. If it is not an optional you can't use the exclamation point.

@Connor 2014-06-03 15:12:39

I edited my answer to make this more clear

@Troy 2014-06-03 15:41:53

If I must use an exclamation point for ALL optional vars, then why did Apple even bother with it, as opposed to making it so the lack of an exclamation point means the same thing? It seems like needless bloat... Or is there a case where it makes sense to NOT use an exclamation point with an optional var?

@Connor 2014-06-03 15:44:51

you use the exclamation point when you need the optional to be not nil. Like in the case with accessing properties of john. you could do something like var jack: Person? = john where jack is also an optional or var jack: Person = john! where jack is a Person and is not nil

@Troy 2014-06-03 16:29:51

Right but, in the original example, doesn't the fact that I'm dereferencing the john optional tell the compiler that I need it to be non-nil?... And in your var jack: Person = john! example, doesn't the lack of a ? after Person tell the compiler that you need john to be non-nil? Overall, the ! just seems seems kind of redundant... It still feels like I'm missing something on the "why" part of !...

@Richard Washington 2014-06-07 00:09:12

"f john is an optional you must use the exclamation point to access its properties" - actually you don't need to. Take it off and see for yourself - it still returns 123 as expected.

@Richard Washington 2014-06-07 00:14:22

In fact later on the docs talk about implicitly unwrapped optionals using the below example: “let possibleString: String? = "An optional string." println(possibleString!) // requires an exclamation mark to access its value // prints "An optional string.” But it works fine with no !. Something seems odd here.

@Ben Gottlieb 2014-06-03 15:00:36

If john were an optional var (declared thusly)

var john: Person?

then it would be possible for john to have no value (in ObjC parlance, nil value)

The exclamation point basically tells the compiler "I know this has a value, you don't need to test for it". If you didn't want to use it, you could conditionally test for it:

if let otherPerson = john {
    otherPerson.apartment = number73
}

The interior of this will only evaluate if john has a value.

@Troy 2014-06-03 15:33:49

Thanks for the response, I now understand what the exclamation mark says, I'm still trying to wrap my head around why... You said it tells the compiler "I know this has a value, you don't need to test for it". What does it buy me when the compiler doesn't test for it? Without the exclamation point, is the compiler going to throw an error (I don't have an environment, yet, where I can test Swift)? Is the ! 100% necessary for all optional vars? If so, why did Apple bother with it, as opposed to just making it so the lack of ! means "I know this has a value, you don't need to test for it"?

@Richard Washington 2014-06-07 00:07:11

"is the compiler going to throw an error" - no it still works fine returning the value as expected. I don't get this. Is the ! just for speed when you are sure maybe?

@Richard Washington 2014-06-07 00:14:53

In fact later on the docs talk about implicitly unwrapped optionals using the below example: “let possibleString: String? = "An optional string." println(possibleString!) // requires an exclamation mark to access its value // prints "An optional string.” But it works fine with no !. Something seems odd here.

@mbeaty 2014-06-07 08:28:59

@RichardWashington You're confused for good reason! The examples in the docs are leaving some things out, and are misleading because all they do is use println. Apparently, there are at least a couple of instances where unwrapping of optionals is not required. One is when using println. Another is when using string interpolation. So, maybe println and string interpolation are unwrapping under the covers? Maybe someone has more insight on this. Looking at the Xcode6 Beta header definitions didn't reveal to me anything about this magic.

@Richard Washington 2014-06-07 09:15:20

Yes, I get that John? and John are two different types. One is of type Optional Person and the other Type Person. Optional Person needs to be unwrapped before you can get Person out. But as you say, this seems to happen at least in these circumstances without having to actually do anything. This seems to make the ! redundant. Unless the ! is ALWAYS optional but a suggested thing to do to catch compile time errors. Kind of like assigning vars/lets to a particular type can be explicit let John: Person = ... but can also be inferred let John = ....

Related Questions

Sponsored Content

40 Answered Questions

[SOLVED] Get nth character of a string in Swift programming language

11 Answered Questions

20 Answered Questions

[SOLVED] #pragma mark in Swift?

  • 2014-06-03 14:05:56
  • Arbitur
  • 213237 View
  • 907 Score
  • 20 Answer
  • Tags:   swift

25 Answered Questions

[SOLVED] How does one generate a random number in Apple's Swift language?

  • 2014-06-03 04:27:24
  • door_number_three
  • 295805 View
  • 418 Score
  • 25 Answer
  • Tags:   swift random

16 Answered Questions

[SOLVED] #ifdef replacement in the Swift language

13 Answered Questions

[SOLVED] What is an optional value in Swift?

  • 2014-06-02 21:32:29
  • Tim Vermeulen
  • 132117 View
  • 258 Score
  • 13 Answer
  • Tags:   swift optional

0 Answered Questions

Xcode playground compilation flow

1 Answered Questions

[SOLVED] What does an exclamation mark in a property in Swift language?

  • 2014-06-18 13:17:55
  • Artem Abramov
  • 16976 View
  • 44 Score
  • 1 Answer
  • Tags:   swift

1 Answered Questions

[SOLVED] Swift variable decorations with "?" (question mark) and "!" (exclamation mark)

  • 2014-06-09 14:36:45
  • Jason Renaldo
  • 23623 View
  • 103 Score
  • 1 Answer
  • Tags:   swift optional

3 Answered Questions

[SOLVED] What does the exclamation mark mean for a swift initializer?

  • 2014-10-18 13:57:24
  • Mike Lischke
  • 2525 View
  • 13 Score
  • 3 Answer
  • Tags:   objective-c swift

Sponsored Content