What does “fatal error: unexpectedly found nil while unwrapping an Optional value” mean?
My Swift program is crashing with EXC_BAD_INSTRUCTION
and this error. What does it mean, and how do I fix it?
fatal error: unexpectedly found nil while unwrapping an Optional value
This post is intended to collect answers to "unexpectedly found nil" issues, so they are not scattered and hard to find. Feel free to add your own answer or edit the existing wiki answer.
swift exception optional
add a comment |
My Swift program is crashing with EXC_BAD_INSTRUCTION
and this error. What does it mean, and how do I fix it?
fatal error: unexpectedly found nil while unwrapping an Optional value
This post is intended to collect answers to "unexpectedly found nil" issues, so they are not scattered and hard to find. Feel free to add your own answer or edit the existing wiki answer.
swift exception optional
5
@RobertColumbia, this is a Community Wiki Q&A pair with extensive documentation of the issue, I don't think this question should be closed for a lack of a MCVE.
– JAL
Sep 25 '17 at 0:44
add a comment |
My Swift program is crashing with EXC_BAD_INSTRUCTION
and this error. What does it mean, and how do I fix it?
fatal error: unexpectedly found nil while unwrapping an Optional value
This post is intended to collect answers to "unexpectedly found nil" issues, so they are not scattered and hard to find. Feel free to add your own answer or edit the existing wiki answer.
swift exception optional
My Swift program is crashing with EXC_BAD_INSTRUCTION
and this error. What does it mean, and how do I fix it?
fatal error: unexpectedly found nil while unwrapping an Optional value
This post is intended to collect answers to "unexpectedly found nil" issues, so they are not scattered and hard to find. Feel free to add your own answer or edit the existing wiki answer.
swift exception optional
swift exception optional
edited May 19 at 14:26
community wiki
8 revs, 5 users 58%
jtbandes
5
@RobertColumbia, this is a Community Wiki Q&A pair with extensive documentation of the issue, I don't think this question should be closed for a lack of a MCVE.
– JAL
Sep 25 '17 at 0:44
add a comment |
5
@RobertColumbia, this is a Community Wiki Q&A pair with extensive documentation of the issue, I don't think this question should be closed for a lack of a MCVE.
– JAL
Sep 25 '17 at 0:44
5
5
@RobertColumbia, this is a Community Wiki Q&A pair with extensive documentation of the issue, I don't think this question should be closed for a lack of a MCVE.
– JAL
Sep 25 '17 at 0:44
@RobertColumbia, this is a Community Wiki Q&A pair with extensive documentation of the issue, I don't think this question should be closed for a lack of a MCVE.
– JAL
Sep 25 '17 at 0:44
add a comment |
8 Answers
8
active
oldest
votes
This answer is community wiki. If you feel it could be made better, feel free to edit it!
Background: What’s an Optional?
In Swift, Optional
is a generic type that can contain a value (of any kind), or no value at all.
In many other programming languages, a particular "sentinel" value is often used to indicate a lack of a value. In Objective-C, for example, nil
(the null pointer) indicates the lack of an object. But this gets more tricky when working with primitive types — should -1
be used to indicate the absence of an integer, or perhaps INT_MIN
, or some other integer? If any particular value is chosen to mean "no integer", that means it can no longer be treated as a valid value.
Swift is a type-safe language, which means the language helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake.
In Swift, any type can be made optional. An optional value can take on any value from the original type, or the special value nil
.
Optionals are defined with a ?
suffix on the type:
var anInt: Int = 42
var anOptionalInt: Int? = 42
var anotherOptionalInt: Int? // `nil` is the default when no value is provided
The lack of a value in an optional is indicated by nil
:
anOptionalInt = nil
(Note that this nil
is not the same as the nil
in Objective-C. In Objective-C, nil
is the absence of a valid object pointer; in Swift, Optionals are not restricted to objects/reference types. Optional behaves similarly to Haskell's Maybe.)
Why did I get “fatal error: unexpectedly found nil while unwrapping an Optional value”?
In order to access an optional’s value (if it has one at all), you need to unwrap it. An optional value can be unwrapped safely or forcibly. If you force-unwrap an optional, and it didn't have a value, your program will crash with the above message.
Xcode will show you the crash by highlighting a line of code. The problem occurs on this line.
This crash can occur with two different kinds of force-unwrap:
1. Explicit Force Unwrapping
This is done with the !
operator on an optional. For example:
let anOptionalString: String?
print(anOptionalString!) // <- CRASH
As anOptionalString
is nil
here, you will get a crash on the line where you force unwrap it.
2. Implicitly Unwrapped Optionals
These are defined with a !
, rather than a ?
after the type.
var optionalDouble: Double! // this value is implicitly unwrapped wherever it's used
These optionals are assumed to contain a value. Therefore whenever you access an implicitly unwrapped optional, it will automatically be force unwrapped for you. If it doesn’t contain a value, it will crash.
print(optionalDouble) // <- CRASH
In order to work out which variable caused the crash, you can hold ⌥ while clicking to show the definition, where you might find the optional type.
IBOutlets, in particular, are usually implicitly unwrapped optionals. This is because your xib or storyboard will link up the outlets at runtime, after initialization. You should therefore ensure that you’re not accessing outlets before they're loaded in. You also should check that the connections are correct in your storyboard/xib file, otherwise the values will be nil
at runtime, and therefore crash when they are implicitly unwrapped.
When should I ever force unwrap an Optional?
Explicit Force Unwrapping
As a general rule, you should never explicitly force unwrap an optional with the !
operator. There may be cases where using !
is acceptable – but you should only ever be using it if you are 100% sure that the optional contains a value.
While there may be an occasion where you can use force unwrapping, as you know for a fact that an optional contains a value – there is not a single place where you cannot safely unwrap that optional instead.
Implicitly Unwrapped Optionals
These variables are designed so that you can defer their assignment until later in your code. It is your responsibility to ensure they have a value before you access them. However, because they involve force unwrapping, they are still inherently unsafe – as they assume your value is non-nil, even though assigning nil is valid.
You should only be using implicitly unwrapped optionals as a last resort. If you can use a lazy variable, or provide a default value for a variable – you should do so instead of using an implicitly unwrapped optional.
However, there are a few scenarios where implicitly unwrapped optionals are beneficial, and you are still able to use various ways of safely unwrapping them as listed below – but you should always use them with due caution.
How can I safely deal with Optionals?
The simplest way to check whether an optional contains a value, is to compare it to nil
.
if anOptionalInt != nil {
print("Contains a value!")
} else {
print("Doesn’t contain a value.")
}
However, 99.9% of the time when working with optionals, you’ll actually want to access the value it contains, if it contains one at all. To do this, you can use Optional Binding.
Optional Binding
Optional Binding allows you to check if an optional contains a value – and allows you to assign the unwrapped value to a new variable or constant. It uses the syntax if let x = anOptional {...}
or if var x = anOptional {...}
, depending if you need to modify the value of the new variable after binding it.
For example:
if let number = anOptionalInt {
print("Contains a value! It is (number)!")
} else {
print("Doesn’t contain a number")
}
What this does is first check that the optional contains a value. If it does, then the ‘unwrapped’ value is assigned to a new variable (number
) – which you can then freely use as if it were non-optional. If the optional doesn’t contain a value, then the else clause will be invoked, as you would expect.
What’s neat about optional binding, is you can unwrap multiple optionals at the same time. You can just separate the statements with a comma. The statement will succeed if all the optionals were unwrapped.
var anOptionalInt : Int?
var anOptionalString : String?
if let number = anOptionalInt, let text = anOptionalString {
print("anOptionalInt contains a value: (number). And so does anOptionalString, it’s: (text)")
} else {
print("One or more of the optionals don’t contain a value")
}
Another neat trick is that you can also use commas to check for a certain condition on the value, after unwrapping it.
if let number = anOptionalInt, number > 0 {
print("anOptionalInt contains a value: (number), and it’s greater than zero!")
}
The only catch with using optional binding within an if statement, is that you can only access the unwrapped value from within the scope of the statement. If you need access to the value from outside of the scope of the statement, you can use a guard statement.
A guard statement allows you to define a condition for success – and the current scope will only continue executing if that condition is met. They are defined with the syntax guard condition else {...}
.
So, to use them with an optional binding, you can do this:
guard let number = anOptionalInt else {
return
}
(Note that within the guard body, you must use one of the control transfer statements in order to exit the scope of the currently executing code).
If anOptionalInt
contains a value, it will be unwrapped and assigned to the new number
constant. The code after the guard will then continue executing. If it doesn’t contain a value – the guard will execute the code within the brackets, which will lead to transfer of control, so that the code immediately after will not be executed.
The real neat thing about guard statements is the unwrapped value is now available to use in code that follows the statement (as we know that future code can only execute if the optional has a value). This is a great for eliminating ‘pyramids of doom’ created by nesting multiple if statements.
For example:
guard let number = anOptionalInt else {
return
}
print("anOptionalInt contains a value, and it’s: (number)!")
Guards also support the same neat tricks that the if statement supported, such as unwrapping multiple optionals at the same time and using the where
clause.
Whether you use an if or guard statement completely depends on whether any future code requires the optional to contain a value.
Nil Coalescing Operator
The Nil Coalescing Operator is a nifty shorthand version of the ternary conditional operator, primarily designed to convert optionals to non-optionals. It has the syntax a ?? b
, where a
is an optional type and b
is the same type as a
(although usually non-optional).
It essentially lets you say “If a
contains a value, unwrap it. If it doesn’t then return b
instead”. For example, you could use it like this:
let number = anOptionalInt ?? 0
This will define a number
constant of Int
type, that will either contain the value of anOptionalInt
, if it contains a value, or 0
otherwise.
It’s just shorthand for:
let number = anOptionalInt != nil ? anOptionalInt! : 0
Optional Chaining
You can use Optional Chaining in order to call a method or access a property on an optional. This is simply done by suffixing the variable name with a ?
when using it.
For example, say we have a variable foo
, of type an optional Foo
instance.
var foo : Foo?
If we wanted to call a method on foo
that doesn’t return anything, we can simply do:
foo?.doSomethingInteresting()
If foo
contains a value, this method will be called on it. If it doesn’t, nothing bad will happen – the code will simply continue executing.
(This is similar behaviour to sending messages to nil
in Objective-C)
This can therefore also be used to set properties as well as call methods. For example:
foo?.bar = Bar()
Again, nothing bad will happen here if foo
is nil
. Your code will simply continue executing.
Another neat trick that optional chaining lets you do is check whether setting a property or calling a method was successful. You can do this by comparing the return value to nil
.
(This is because an optional value will return Void?
rather than Void
on a method that doesn’t return anything)
For example:
if (foo?.bar = Bar()) != nil {
print("bar was set successfully")
} else {
print("bar wasn’t set successfully")
}
However, things become a little bit more tricky when trying to access properties or call methods that return a value. Because foo
is optional, anything returned from it will also be optional. To deal with this, you can either unwrap the optionals that get returned using one of the above methods – or unwrap foo
itself before accessing methods or calling methods that return values.
Also, as the name suggests, you can ‘chain’ these statements together. This means that if foo
has an optional property baz
, which has a property qux
– you could write the following:
let optionalQux = foo?.baz?.qux
Again, because foo
and baz
are optional, the value returned from qux
will always be an optional regardless of whether qux
itself is optional.
map
and flatMap
An often underused feature with optionals is the ability to use the map
and flatMap
functions. These allow you to apply non-optional transforms to optional variables. If an optional has a value, you can apply a given transformation to it. If it doesn’t have a value, it will remain nil
.
For example, let’s say you have an optional string:
let anOptionalString:String?
By applying the map
function to it – we can use the stringByAppendingString
function in order to concatenate it to another string.
Because stringByAppendingString
takes a non-optional string argument, we cannot input our optional string directly. However, by using map
, we can use allow stringByAppendingString
to be used if anOptionalString
has a value.
For example:
var anOptionalString:String? = "bar"
anOptionalString = anOptionalString.map {unwrappedString in
return "foo".stringByAppendingString(unwrappedString)
}
print(anOptionalString) // Optional("foobar")
However, if anOptionalString
doesn’t have a value, map
will return nil
. For example:
var anOptionalString:String?
anOptionalString = anOptionalString.map {unwrappedString in
return "foo".stringByAppendingString(unwrappedString)
}
print(anOptionalString) // nil
flatMap
works similarly to map
, except it allows you to return another optional from within the closure body. This means you can input an optional into a process that requires a non-optional input, but can output an optional itself.
try!
Swift's error handling system can be safely used with Do-Try-Catch:
do {
let result = try someThrowingFunc()
} catch {
print(error)
}
If someThrowingFunc()
throws an error, the error will be safely caught in the catch
block.
The error
constant you see in the catch
block has not been declared by us - it's automatically generated by catch
.
You can also declare error
yourself, it has the advantage of being able to cast it to a useful format, for example:
do {
let result = try someThrowingFunc()
} catch let error as NSError {
print(error.debugDescription)
}
Using try
this way is the proper way to try, catch and handle errors coming from throwing functions.
There's also try?
which absorbs the error:
if let result = try? someThrowingFunc() {
// cool
} else {
// handle the failure, but there's no error information available
}
But Swift's error handling system also provides a way to "force try" with try!
:
let result = try! someThrowingFunc()
The concepts explained in this post also apply here: if an error is thrown, the application will crash.
You should only ever use try!
if you can prove that its result will never fail in your context - and this is very rare.
Most of the time you will use the complete Do-Try-Catch system - and the optional one, try?
, in the rare cases where handling the error is not important.
Resources
- Apple documentation on Swift Optionals
- When to use and when not to use implicitly unwrapped optionals
- Learn how to debug an iOS app crash
63
Personally, I would like to thank you for putting in the effort to write all of this. I feel like this will certainly be helpful to beginners and experts alike using swift.
– Pranav Wadhwa
Jun 6 '16 at 1:27
12
I'm glad you found it helpful. This answer is community wiki, so it's a collaboration between many people (7, so far)!
– jtbandes
Jun 6 '16 at 4:44
This error is intermittent in my case. Any suggestions? Code in stackoverflow.com/questions/50933681/…
– py_ios_dev
Jun 19 at 17:12
Perhaps it's time to update this answer to usecompactMap()
instead offlatMap()
.
– Nicolas Miari
Sep 19 at 5:48
add a comment |
TL;DR answer
With very few exceptions, this rule is golden:
Avoid use of !
Declare variable optional (?
), not implicitly unwrapped optionals (IUO) (!
)
In other words, rather use:var nameOfDaughter: String?
Instead of:var nameOfDaughter: String!
Unwrap optional variable using if let
or guard let
Either unwrap variable like this:
if let nameOfDaughter = nameOfDaughter {
print("My daughters name is: (nameOfDaughter)")
}
Or like this:
guard let nameOfDaughter = nameOfDaughter else { return }
print("My daughters name is: (nameOfDaughter)")
This answer was intended to be concise, for full comprehension read accepted answer
add a comment |
This question comes up ALL THE TIME on SO. It's one of the first things that new Swift developers struggle with.
Background:
Swift uses the concept of "Optionals" to deal with values that could contain a value, or not. In other languages like C, you might store a value of 0 in a variable to indicate that it contains no value. However, what if 0 is a valid value? Then you might use -1. What if -1 is a valid value? And so on.
Swift optionals let you set up a variable of any type to contain either a valid value, or no value.
You put a question mark after the type when you declare a variable to mean (type x, or no value).
An optional is actually a container than contains either a variable of a given type, or nothing.
An optional needs to be "unwrapped" in order to fetch the value inside.
The "!" operator is a "force unwrap" operator. It says "trust me. I know what I am doing. I guarantee that when this code runs, the variable will not contain nil." If you are wrong, you crash.
Unless you really do know what you are doing, avoid the "!" force unwrap operator. It is probably the largest source of crashes for beginning Swift programmers.
How to deal with optionals:
There are lots of other ways of dealing with optionals that are safer. Here are some (not an exhaustive list)
You can use "optional binding" or "if let" to say "if this optional contains a value, save that value into a new, non-optional variable. If the optional does not contain a value, skip the body of this if statement".
Here is an example of optional binding with our foo
optional:
if let newFoo = foo //If let is called optional binding. {
print("foo is not nil")
} else {
print("foo is nil")
}
Note that the variable you define when you use optional biding only exists (is only "in scope") in the body of the if statement.
Alternately, you could use a guard statement, which lets you exit your function if the variable is nil:
func aFunc(foo: Int?) {
guard let newFoo = input else { return }
//For the rest of the function newFoo is a non-optional var
}
Guard statements were added in Swift 2. Guard lets you preserve the "golden path" through your code, and avoid ever-increasing levels of nested ifs that sometimes result from using "if let" optional binding.
There is also a construct called the "nil coalescing operator". It takes the form "optional_var ?? replacement_val". It returns a non-optional variable with the same type as the data contained in the optional. If the optional contains nil, it returns the value of the expression after the "??" symbol.
So you could use code like this:
let newFoo = foo ?? "nil" // "??" is the nil coalescing operator
print("foo = (newFoo)")
You could also use try/catch or guard error handling, but generally one of the other techniques above is cleaner.
EDIT:
Another, slightly more subtle gotcha with optionals is "implicitly unwrapped optionals. When we declare foo, we could say:
var foo: String!
In that case foo is still an optional, but you don't have to unwrap it to reference it. That means any time you try to reference foo, you crash if it's nil.
So this code:
var foo: String!
let upperFoo = foo.capitalizedString
Will crash on reference to foo's capitalizedString property even though we're not force-unwrapping foo. the print looks fine, but it's not.
Thus you want to be really careful with implicitly unwrapped optionals. (and perhaps even avoid them completely until you have a solid understanding of optionals.)
Bottom line: When you are first learning Swift, pretend the "!" character is not part of the language. It's likely to get you into trouble.
7
You should consider making this a public wiki.
– vacawama
Feb 28 '16 at 14:42
3
Edit your answer, and below the edit box on the right is a community wiki checkbox. You will no longer get rep for the answer, but I know this isn't a blatant rep grab anyway.
– vacawama
Feb 28 '16 at 14:49
2
meta.stackexchange.com/q/11740/200104
– vacawama
Feb 28 '16 at 14:55
6
Given that this question is asked a million times on the site, if I were going to take the time to post a self-answered question as the canonical answer to the question, I'd hope that the answer is far more complete than this. There's nothing aboutguard
clauses. There's nothing about use ofif var
which is just as valid a construct asif let
. There's nothing aboutwhere
clauses which I feel is worth mention when we're talking aboutif let
binding (it removes a whole layer of nesting in many cases). There's nothing about optional chaining.
– nhgrif
Feb 28 '16 at 22:00
6
And when you mention implicitly unwrapped optionals, you don't even mention that you can use all of the aforementioned optional tricks to safely unwrap implicitly unwrapped optionals. We also don't cover unwrapping multiple options in the same clause.
– nhgrif
Feb 28 '16 at 22:01
|
show 4 more comments
First, you should know what an Optional value is.
You can step to The Swift Programming Launage
for detail.
Second, you should know the optional value has two status. One is the full value, and the other is nil value. So before you implement an optional value, you should check which state it's.
You can use if let ...
or guard let ... else
and so on.
One other way, if you don't want to check it's state before your implement, you can also use var buildingName = buildingName ?? "buildingName"
instead.
add a comment |
Since the above answers clearly explains how to play safely with Optionals.
I will try explain what Optionals are really in swift.
Another way to declare an optional variable is
var i : Optional<Int>
And Optional type is nothing but an enumeration with two cases, i.e
enum Optional<Wrapped> : ExpressibleByNilLiteral {
case none
case some(Wrapped)
.
.
.
}
So to assign a nil to our variable 'i'. We can do
var i = Optional<Int>.none
or to assign a value, we will pass some value
var i = Optional<Int>.some(28)
According to swift, 'nil' is the absence of value.
And to create an instance initialized with nil
We have to conform to a protocol called ExpressibleByNilLiteral
and great if you guessed it, only Optionals
conform to ExpressibleByNilLiteral
and conforming to other types is discouraged.
ExpressibleByNilLiteral
has a single method called init(nilLiteral:)
which initializes an instace with nil. You usually wont call this method and according to swift documentation it is discouraged to call this initializer directly as the compiler calls it whenever you initialize an Optional type with nil
literal.
Even myself has to wrap (no pun intended) my head around Optionals :D
Happy Swfting All.
add a comment |
I had this error once when I was trying to set my Outlets values from the prepare for segue method as follows:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? DestinationVC{
if let item = sender as? DataItem{
// This line pops up the error
destination.nameLabel.text = item.name
}
}
}
Then I found out that I can't set the values of the destination controller outlets because the controller hasn't been loaded or initialized yet.
So I solved it this way:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? DestinationVC{
if let item = sender as? DataItem{
// Created this method in the destination Controller to update its outlets after it's being initialized and loaded
destination.updateView(itemData: item)
}
}
}
Destination Controller:
// This variable to hold the data received to update the Label text after the VIEW DID LOAD
var name = ""
// Outlets
@IBOutlet weak var nameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
nameLabel.text = name
}
func updateView(itemDate: ObjectModel) {
name = itemDate.name
}
I hope this answer helps anyone out there with the same issue as I found the marked answer is great resource to the understanding of optionals and how they work but hasn't addressed the issue itself directly.
add a comment |
Basically you tried to use a nil value in places where Swift allows only non-nil ones, by "fooling" the compiler to think there is nil value there, thus allowing your app to compile.
There are several scenarios that lead to this kind of fatal error:
forced unwraps:
let user = someVariable!
If
someVariable
is nil, then you'll get a crash. By doing a force unwrap you moved the nil check responsibility from the compiler to you, basically by doing a forced unwrap you're guaranteeing to the compiler that you'll never have nil values there. And guess what it happens if this happens?
Solution? Use optional binding (aka if-let), do the variable processing there:
if user = someVariable {
// do your stuff
}
forced casts:
let myRectangle = someShape as! Rectangle
Here by force casting you tell the compiler to no longer worry, as you'll always have a
Rectangle
instance there. And as long as that holds, you don't have to worry. The problems start when you or your colleagues from the project start circulating non-rectangle values.
Solution? Use optional binding (aka if-let), do the variable processing there:
if let myRectangle = someShape as? Rectangle {
// yay, I have a rectangle
}
Implicitly unwrapped optionals. Let's assume you have the following class definition:
class User {
var name: String!
init() {
name = "none yet"
}
func nicerName() {
return "Mr/Ms " + name
}
}
Now, if no-one messes up with the
name
property by setting it tonil
, then it works as expected, however ifUser
is initialized from a JSON that lacks thename
key, then you get the fatal error when trying to use the property.
Solution? Don't use them :) Unless you're 102% sure that the property will always have a non-nil value by the time it needs to be used. However in most cases converting it to an optional or non-optional will work. Making it non-optional will also result in the compiler helping you by telling the code paths you missed giving a value to that property
Unconnected outlets. This is a particular case of scenario #3. Basically you have some XIB-loaded class that you want to use.
class SignInViewController: UIViewController {
@IBOutlet var emailTextField: UITextField!
}
Now if you missed connecting the outlet from the XIB editor, then the app will crash as soon as you'll want to use the outlet.
Solution? Make sure all outlets are connected. Or use the?
operator on them:emailTextField?.text = "my@email.com"
. Or declare the outlet as optional, though in this case the compiler will force you to unwrap it all over the code.
Values coming from Objective-C, and that don't have nullability annotations. Let's assume we have the following Objective-C class:
@interface User: NSObject
@property NSString *name;
@end
Now if no nullability annotations are specified (either explicitly or via
NS_ASSUME_NONNULL_BEGIN
/NS_ASSUME_NONNULL_END
), then thename
property will be imported in Swift asString!
(an IUO - implicitly unwrapped optional). As soon as some swift code will want to use the value, it will crash, in nil cases.
Solution? Add nullability annotations to your Objective-C code. Beware though, the Objective-C compiler is a little bit permissive when it comes to nullability, you might end up with nil values, even if you explicitly marked them as
nonnull
.
add a comment |
This is more of a important comment and that why implicitly unwrapped optionals can be deceptive when it comes to debugging nil
values.
Think of the following code:
It compiles with no errors/warnings:
c1.address.city = c3.address.city
Yet at runtime it gives the following error: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Can you tell me which object is nil
?
You can't!
The full code would be:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var c1 = NormalContact()
let c3 = BadContact()
c1.address.city = c3.address.city // compiler hides the truth from you and then you sudden get a crash
}
}
struct NormalContact {
var address : Address = Address(city: "defaultCity")
}
struct BadContact {
var address : Address!
}
struct Address {
var city : String
}
Long story short by using var address : Address!
you're hiding the possibility that a variable can be nil
from other readers. And when it crashes you're like "what the hell?! my address
isn't an optional, so why am I crashing?!.
Hence it's better to write as such:
c1.address.city = c2.address!.city // ERROR: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Can you now tell me which object it is that was nil
?
This time the code has been made more clear to you. You can rationalize and think that likely it's the address
parameter that was forcefully unwrapped.
The full code would be :
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var c1 = NormalContact()
let c2 = GoodContact()
c1.address.city = c2.address!.city
c1.address.city = c2.address?.city // not compile-able. No deceiving by the compiler
c1.address.city = c2.address.city // not compile-able. No deceiving by the compiler
if let city = c2.address?.city { // safest approach. But that's not what I'm talking about here.
c1.address.city = city
}
}
}
struct NormalContact {
var address : Address = Address(city: "defaultCity")
}
struct GoodContact {
var address : Address?
}
struct Address {
var city : String
}
add a comment |
protected by jtbandes Jul 30 '16 at 19:56
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
8 Answers
8
active
oldest
votes
8 Answers
8
active
oldest
votes
active
oldest
votes
active
oldest
votes
This answer is community wiki. If you feel it could be made better, feel free to edit it!
Background: What’s an Optional?
In Swift, Optional
is a generic type that can contain a value (of any kind), or no value at all.
In many other programming languages, a particular "sentinel" value is often used to indicate a lack of a value. In Objective-C, for example, nil
(the null pointer) indicates the lack of an object. But this gets more tricky when working with primitive types — should -1
be used to indicate the absence of an integer, or perhaps INT_MIN
, or some other integer? If any particular value is chosen to mean "no integer", that means it can no longer be treated as a valid value.
Swift is a type-safe language, which means the language helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake.
In Swift, any type can be made optional. An optional value can take on any value from the original type, or the special value nil
.
Optionals are defined with a ?
suffix on the type:
var anInt: Int = 42
var anOptionalInt: Int? = 42
var anotherOptionalInt: Int? // `nil` is the default when no value is provided
The lack of a value in an optional is indicated by nil
:
anOptionalInt = nil
(Note that this nil
is not the same as the nil
in Objective-C. In Objective-C, nil
is the absence of a valid object pointer; in Swift, Optionals are not restricted to objects/reference types. Optional behaves similarly to Haskell's Maybe.)
Why did I get “fatal error: unexpectedly found nil while unwrapping an Optional value”?
In order to access an optional’s value (if it has one at all), you need to unwrap it. An optional value can be unwrapped safely or forcibly. If you force-unwrap an optional, and it didn't have a value, your program will crash with the above message.
Xcode will show you the crash by highlighting a line of code. The problem occurs on this line.
This crash can occur with two different kinds of force-unwrap:
1. Explicit Force Unwrapping
This is done with the !
operator on an optional. For example:
let anOptionalString: String?
print(anOptionalString!) // <- CRASH
As anOptionalString
is nil
here, you will get a crash on the line where you force unwrap it.
2. Implicitly Unwrapped Optionals
These are defined with a !
, rather than a ?
after the type.
var optionalDouble: Double! // this value is implicitly unwrapped wherever it's used
These optionals are assumed to contain a value. Therefore whenever you access an implicitly unwrapped optional, it will automatically be force unwrapped for you. If it doesn’t contain a value, it will crash.
print(optionalDouble) // <- CRASH
In order to work out which variable caused the crash, you can hold ⌥ while clicking to show the definition, where you might find the optional type.
IBOutlets, in particular, are usually implicitly unwrapped optionals. This is because your xib or storyboard will link up the outlets at runtime, after initialization. You should therefore ensure that you’re not accessing outlets before they're loaded in. You also should check that the connections are correct in your storyboard/xib file, otherwise the values will be nil
at runtime, and therefore crash when they are implicitly unwrapped.
When should I ever force unwrap an Optional?
Explicit Force Unwrapping
As a general rule, you should never explicitly force unwrap an optional with the !
operator. There may be cases where using !
is acceptable – but you should only ever be using it if you are 100% sure that the optional contains a value.
While there may be an occasion where you can use force unwrapping, as you know for a fact that an optional contains a value – there is not a single place where you cannot safely unwrap that optional instead.
Implicitly Unwrapped Optionals
These variables are designed so that you can defer their assignment until later in your code. It is your responsibility to ensure they have a value before you access them. However, because they involve force unwrapping, they are still inherently unsafe – as they assume your value is non-nil, even though assigning nil is valid.
You should only be using implicitly unwrapped optionals as a last resort. If you can use a lazy variable, or provide a default value for a variable – you should do so instead of using an implicitly unwrapped optional.
However, there are a few scenarios where implicitly unwrapped optionals are beneficial, and you are still able to use various ways of safely unwrapping them as listed below – but you should always use them with due caution.
How can I safely deal with Optionals?
The simplest way to check whether an optional contains a value, is to compare it to nil
.
if anOptionalInt != nil {
print("Contains a value!")
} else {
print("Doesn’t contain a value.")
}
However, 99.9% of the time when working with optionals, you’ll actually want to access the value it contains, if it contains one at all. To do this, you can use Optional Binding.
Optional Binding
Optional Binding allows you to check if an optional contains a value – and allows you to assign the unwrapped value to a new variable or constant. It uses the syntax if let x = anOptional {...}
or if var x = anOptional {...}
, depending if you need to modify the value of the new variable after binding it.
For example:
if let number = anOptionalInt {
print("Contains a value! It is (number)!")
} else {
print("Doesn’t contain a number")
}
What this does is first check that the optional contains a value. If it does, then the ‘unwrapped’ value is assigned to a new variable (number
) – which you can then freely use as if it were non-optional. If the optional doesn’t contain a value, then the else clause will be invoked, as you would expect.
What’s neat about optional binding, is you can unwrap multiple optionals at the same time. You can just separate the statements with a comma. The statement will succeed if all the optionals were unwrapped.
var anOptionalInt : Int?
var anOptionalString : String?
if let number = anOptionalInt, let text = anOptionalString {
print("anOptionalInt contains a value: (number). And so does anOptionalString, it’s: (text)")
} else {
print("One or more of the optionals don’t contain a value")
}
Another neat trick is that you can also use commas to check for a certain condition on the value, after unwrapping it.
if let number = anOptionalInt, number > 0 {
print("anOptionalInt contains a value: (number), and it’s greater than zero!")
}
The only catch with using optional binding within an if statement, is that you can only access the unwrapped value from within the scope of the statement. If you need access to the value from outside of the scope of the statement, you can use a guard statement.
A guard statement allows you to define a condition for success – and the current scope will only continue executing if that condition is met. They are defined with the syntax guard condition else {...}
.
So, to use them with an optional binding, you can do this:
guard let number = anOptionalInt else {
return
}
(Note that within the guard body, you must use one of the control transfer statements in order to exit the scope of the currently executing code).
If anOptionalInt
contains a value, it will be unwrapped and assigned to the new number
constant. The code after the guard will then continue executing. If it doesn’t contain a value – the guard will execute the code within the brackets, which will lead to transfer of control, so that the code immediately after will not be executed.
The real neat thing about guard statements is the unwrapped value is now available to use in code that follows the statement (as we know that future code can only execute if the optional has a value). This is a great for eliminating ‘pyramids of doom’ created by nesting multiple if statements.
For example:
guard let number = anOptionalInt else {
return
}
print("anOptionalInt contains a value, and it’s: (number)!")
Guards also support the same neat tricks that the if statement supported, such as unwrapping multiple optionals at the same time and using the where
clause.
Whether you use an if or guard statement completely depends on whether any future code requires the optional to contain a value.
Nil Coalescing Operator
The Nil Coalescing Operator is a nifty shorthand version of the ternary conditional operator, primarily designed to convert optionals to non-optionals. It has the syntax a ?? b
, where a
is an optional type and b
is the same type as a
(although usually non-optional).
It essentially lets you say “If a
contains a value, unwrap it. If it doesn’t then return b
instead”. For example, you could use it like this:
let number = anOptionalInt ?? 0
This will define a number
constant of Int
type, that will either contain the value of anOptionalInt
, if it contains a value, or 0
otherwise.
It’s just shorthand for:
let number = anOptionalInt != nil ? anOptionalInt! : 0
Optional Chaining
You can use Optional Chaining in order to call a method or access a property on an optional. This is simply done by suffixing the variable name with a ?
when using it.
For example, say we have a variable foo
, of type an optional Foo
instance.
var foo : Foo?
If we wanted to call a method on foo
that doesn’t return anything, we can simply do:
foo?.doSomethingInteresting()
If foo
contains a value, this method will be called on it. If it doesn’t, nothing bad will happen – the code will simply continue executing.
(This is similar behaviour to sending messages to nil
in Objective-C)
This can therefore also be used to set properties as well as call methods. For example:
foo?.bar = Bar()
Again, nothing bad will happen here if foo
is nil
. Your code will simply continue executing.
Another neat trick that optional chaining lets you do is check whether setting a property or calling a method was successful. You can do this by comparing the return value to nil
.
(This is because an optional value will return Void?
rather than Void
on a method that doesn’t return anything)
For example:
if (foo?.bar = Bar()) != nil {
print("bar was set successfully")
} else {
print("bar wasn’t set successfully")
}
However, things become a little bit more tricky when trying to access properties or call methods that return a value. Because foo
is optional, anything returned from it will also be optional. To deal with this, you can either unwrap the optionals that get returned using one of the above methods – or unwrap foo
itself before accessing methods or calling methods that return values.
Also, as the name suggests, you can ‘chain’ these statements together. This means that if foo
has an optional property baz
, which has a property qux
– you could write the following:
let optionalQux = foo?.baz?.qux
Again, because foo
and baz
are optional, the value returned from qux
will always be an optional regardless of whether qux
itself is optional.
map
and flatMap
An often underused feature with optionals is the ability to use the map
and flatMap
functions. These allow you to apply non-optional transforms to optional variables. If an optional has a value, you can apply a given transformation to it. If it doesn’t have a value, it will remain nil
.
For example, let’s say you have an optional string:
let anOptionalString:String?
By applying the map
function to it – we can use the stringByAppendingString
function in order to concatenate it to another string.
Because stringByAppendingString
takes a non-optional string argument, we cannot input our optional string directly. However, by using map
, we can use allow stringByAppendingString
to be used if anOptionalString
has a value.
For example:
var anOptionalString:String? = "bar"
anOptionalString = anOptionalString.map {unwrappedString in
return "foo".stringByAppendingString(unwrappedString)
}
print(anOptionalString) // Optional("foobar")
However, if anOptionalString
doesn’t have a value, map
will return nil
. For example:
var anOptionalString:String?
anOptionalString = anOptionalString.map {unwrappedString in
return "foo".stringByAppendingString(unwrappedString)
}
print(anOptionalString) // nil
flatMap
works similarly to map
, except it allows you to return another optional from within the closure body. This means you can input an optional into a process that requires a non-optional input, but can output an optional itself.
try!
Swift's error handling system can be safely used with Do-Try-Catch:
do {
let result = try someThrowingFunc()
} catch {
print(error)
}
If someThrowingFunc()
throws an error, the error will be safely caught in the catch
block.
The error
constant you see in the catch
block has not been declared by us - it's automatically generated by catch
.
You can also declare error
yourself, it has the advantage of being able to cast it to a useful format, for example:
do {
let result = try someThrowingFunc()
} catch let error as NSError {
print(error.debugDescription)
}
Using try
this way is the proper way to try, catch and handle errors coming from throwing functions.
There's also try?
which absorbs the error:
if let result = try? someThrowingFunc() {
// cool
} else {
// handle the failure, but there's no error information available
}
But Swift's error handling system also provides a way to "force try" with try!
:
let result = try! someThrowingFunc()
The concepts explained in this post also apply here: if an error is thrown, the application will crash.
You should only ever use try!
if you can prove that its result will never fail in your context - and this is very rare.
Most of the time you will use the complete Do-Try-Catch system - and the optional one, try?
, in the rare cases where handling the error is not important.
Resources
- Apple documentation on Swift Optionals
- When to use and when not to use implicitly unwrapped optionals
- Learn how to debug an iOS app crash
63
Personally, I would like to thank you for putting in the effort to write all of this. I feel like this will certainly be helpful to beginners and experts alike using swift.
– Pranav Wadhwa
Jun 6 '16 at 1:27
12
I'm glad you found it helpful. This answer is community wiki, so it's a collaboration between many people (7, so far)!
– jtbandes
Jun 6 '16 at 4:44
This error is intermittent in my case. Any suggestions? Code in stackoverflow.com/questions/50933681/…
– py_ios_dev
Jun 19 at 17:12
Perhaps it's time to update this answer to usecompactMap()
instead offlatMap()
.
– Nicolas Miari
Sep 19 at 5:48
add a comment |
This answer is community wiki. If you feel it could be made better, feel free to edit it!
Background: What’s an Optional?
In Swift, Optional
is a generic type that can contain a value (of any kind), or no value at all.
In many other programming languages, a particular "sentinel" value is often used to indicate a lack of a value. In Objective-C, for example, nil
(the null pointer) indicates the lack of an object. But this gets more tricky when working with primitive types — should -1
be used to indicate the absence of an integer, or perhaps INT_MIN
, or some other integer? If any particular value is chosen to mean "no integer", that means it can no longer be treated as a valid value.
Swift is a type-safe language, which means the language helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake.
In Swift, any type can be made optional. An optional value can take on any value from the original type, or the special value nil
.
Optionals are defined with a ?
suffix on the type:
var anInt: Int = 42
var anOptionalInt: Int? = 42
var anotherOptionalInt: Int? // `nil` is the default when no value is provided
The lack of a value in an optional is indicated by nil
:
anOptionalInt = nil
(Note that this nil
is not the same as the nil
in Objective-C. In Objective-C, nil
is the absence of a valid object pointer; in Swift, Optionals are not restricted to objects/reference types. Optional behaves similarly to Haskell's Maybe.)
Why did I get “fatal error: unexpectedly found nil while unwrapping an Optional value”?
In order to access an optional’s value (if it has one at all), you need to unwrap it. An optional value can be unwrapped safely or forcibly. If you force-unwrap an optional, and it didn't have a value, your program will crash with the above message.
Xcode will show you the crash by highlighting a line of code. The problem occurs on this line.
This crash can occur with two different kinds of force-unwrap:
1. Explicit Force Unwrapping
This is done with the !
operator on an optional. For example:
let anOptionalString: String?
print(anOptionalString!) // <- CRASH
As anOptionalString
is nil
here, you will get a crash on the line where you force unwrap it.
2. Implicitly Unwrapped Optionals
These are defined with a !
, rather than a ?
after the type.
var optionalDouble: Double! // this value is implicitly unwrapped wherever it's used
These optionals are assumed to contain a value. Therefore whenever you access an implicitly unwrapped optional, it will automatically be force unwrapped for you. If it doesn’t contain a value, it will crash.
print(optionalDouble) // <- CRASH
In order to work out which variable caused the crash, you can hold ⌥ while clicking to show the definition, where you might find the optional type.
IBOutlets, in particular, are usually implicitly unwrapped optionals. This is because your xib or storyboard will link up the outlets at runtime, after initialization. You should therefore ensure that you’re not accessing outlets before they're loaded in. You also should check that the connections are correct in your storyboard/xib file, otherwise the values will be nil
at runtime, and therefore crash when they are implicitly unwrapped.
When should I ever force unwrap an Optional?
Explicit Force Unwrapping
As a general rule, you should never explicitly force unwrap an optional with the !
operator. There may be cases where using !
is acceptable – but you should only ever be using it if you are 100% sure that the optional contains a value.
While there may be an occasion where you can use force unwrapping, as you know for a fact that an optional contains a value – there is not a single place where you cannot safely unwrap that optional instead.
Implicitly Unwrapped Optionals
These variables are designed so that you can defer their assignment until later in your code. It is your responsibility to ensure they have a value before you access them. However, because they involve force unwrapping, they are still inherently unsafe – as they assume your value is non-nil, even though assigning nil is valid.
You should only be using implicitly unwrapped optionals as a last resort. If you can use a lazy variable, or provide a default value for a variable – you should do so instead of using an implicitly unwrapped optional.
However, there are a few scenarios where implicitly unwrapped optionals are beneficial, and you are still able to use various ways of safely unwrapping them as listed below – but you should always use them with due caution.
How can I safely deal with Optionals?
The simplest way to check whether an optional contains a value, is to compare it to nil
.
if anOptionalInt != nil {
print("Contains a value!")
} else {
print("Doesn’t contain a value.")
}
However, 99.9% of the time when working with optionals, you’ll actually want to access the value it contains, if it contains one at all. To do this, you can use Optional Binding.
Optional Binding
Optional Binding allows you to check if an optional contains a value – and allows you to assign the unwrapped value to a new variable or constant. It uses the syntax if let x = anOptional {...}
or if var x = anOptional {...}
, depending if you need to modify the value of the new variable after binding it.
For example:
if let number = anOptionalInt {
print("Contains a value! It is (number)!")
} else {
print("Doesn’t contain a number")
}
What this does is first check that the optional contains a value. If it does, then the ‘unwrapped’ value is assigned to a new variable (number
) – which you can then freely use as if it were non-optional. If the optional doesn’t contain a value, then the else clause will be invoked, as you would expect.
What’s neat about optional binding, is you can unwrap multiple optionals at the same time. You can just separate the statements with a comma. The statement will succeed if all the optionals were unwrapped.
var anOptionalInt : Int?
var anOptionalString : String?
if let number = anOptionalInt, let text = anOptionalString {
print("anOptionalInt contains a value: (number). And so does anOptionalString, it’s: (text)")
} else {
print("One or more of the optionals don’t contain a value")
}
Another neat trick is that you can also use commas to check for a certain condition on the value, after unwrapping it.
if let number = anOptionalInt, number > 0 {
print("anOptionalInt contains a value: (number), and it’s greater than zero!")
}
The only catch with using optional binding within an if statement, is that you can only access the unwrapped value from within the scope of the statement. If you need access to the value from outside of the scope of the statement, you can use a guard statement.
A guard statement allows you to define a condition for success – and the current scope will only continue executing if that condition is met. They are defined with the syntax guard condition else {...}
.
So, to use them with an optional binding, you can do this:
guard let number = anOptionalInt else {
return
}
(Note that within the guard body, you must use one of the control transfer statements in order to exit the scope of the currently executing code).
If anOptionalInt
contains a value, it will be unwrapped and assigned to the new number
constant. The code after the guard will then continue executing. If it doesn’t contain a value – the guard will execute the code within the brackets, which will lead to transfer of control, so that the code immediately after will not be executed.
The real neat thing about guard statements is the unwrapped value is now available to use in code that follows the statement (as we know that future code can only execute if the optional has a value). This is a great for eliminating ‘pyramids of doom’ created by nesting multiple if statements.
For example:
guard let number = anOptionalInt else {
return
}
print("anOptionalInt contains a value, and it’s: (number)!")
Guards also support the same neat tricks that the if statement supported, such as unwrapping multiple optionals at the same time and using the where
clause.
Whether you use an if or guard statement completely depends on whether any future code requires the optional to contain a value.
Nil Coalescing Operator
The Nil Coalescing Operator is a nifty shorthand version of the ternary conditional operator, primarily designed to convert optionals to non-optionals. It has the syntax a ?? b
, where a
is an optional type and b
is the same type as a
(although usually non-optional).
It essentially lets you say “If a
contains a value, unwrap it. If it doesn’t then return b
instead”. For example, you could use it like this:
let number = anOptionalInt ?? 0
This will define a number
constant of Int
type, that will either contain the value of anOptionalInt
, if it contains a value, or 0
otherwise.
It’s just shorthand for:
let number = anOptionalInt != nil ? anOptionalInt! : 0
Optional Chaining
You can use Optional Chaining in order to call a method or access a property on an optional. This is simply done by suffixing the variable name with a ?
when using it.
For example, say we have a variable foo
, of type an optional Foo
instance.
var foo : Foo?
If we wanted to call a method on foo
that doesn’t return anything, we can simply do:
foo?.doSomethingInteresting()
If foo
contains a value, this method will be called on it. If it doesn’t, nothing bad will happen – the code will simply continue executing.
(This is similar behaviour to sending messages to nil
in Objective-C)
This can therefore also be used to set properties as well as call methods. For example:
foo?.bar = Bar()
Again, nothing bad will happen here if foo
is nil
. Your code will simply continue executing.
Another neat trick that optional chaining lets you do is check whether setting a property or calling a method was successful. You can do this by comparing the return value to nil
.
(This is because an optional value will return Void?
rather than Void
on a method that doesn’t return anything)
For example:
if (foo?.bar = Bar()) != nil {
print("bar was set successfully")
} else {
print("bar wasn’t set successfully")
}
However, things become a little bit more tricky when trying to access properties or call methods that return a value. Because foo
is optional, anything returned from it will also be optional. To deal with this, you can either unwrap the optionals that get returned using one of the above methods – or unwrap foo
itself before accessing methods or calling methods that return values.
Also, as the name suggests, you can ‘chain’ these statements together. This means that if foo
has an optional property baz
, which has a property qux
– you could write the following:
let optionalQux = foo?.baz?.qux
Again, because foo
and baz
are optional, the value returned from qux
will always be an optional regardless of whether qux
itself is optional.
map
and flatMap
An often underused feature with optionals is the ability to use the map
and flatMap
functions. These allow you to apply non-optional transforms to optional variables. If an optional has a value, you can apply a given transformation to it. If it doesn’t have a value, it will remain nil
.
For example, let’s say you have an optional string:
let anOptionalString:String?
By applying the map
function to it – we can use the stringByAppendingString
function in order to concatenate it to another string.
Because stringByAppendingString
takes a non-optional string argument, we cannot input our optional string directly. However, by using map
, we can use allow stringByAppendingString
to be used if anOptionalString
has a value.
For example:
var anOptionalString:String? = "bar"
anOptionalString = anOptionalString.map {unwrappedString in
return "foo".stringByAppendingString(unwrappedString)
}
print(anOptionalString) // Optional("foobar")
However, if anOptionalString
doesn’t have a value, map
will return nil
. For example:
var anOptionalString:String?
anOptionalString = anOptionalString.map {unwrappedString in
return "foo".stringByAppendingString(unwrappedString)
}
print(anOptionalString) // nil
flatMap
works similarly to map
, except it allows you to return another optional from within the closure body. This means you can input an optional into a process that requires a non-optional input, but can output an optional itself.
try!
Swift's error handling system can be safely used with Do-Try-Catch:
do {
let result = try someThrowingFunc()
} catch {
print(error)
}
If someThrowingFunc()
throws an error, the error will be safely caught in the catch
block.
The error
constant you see in the catch
block has not been declared by us - it's automatically generated by catch
.
You can also declare error
yourself, it has the advantage of being able to cast it to a useful format, for example:
do {
let result = try someThrowingFunc()
} catch let error as NSError {
print(error.debugDescription)
}
Using try
this way is the proper way to try, catch and handle errors coming from throwing functions.
There's also try?
which absorbs the error:
if let result = try? someThrowingFunc() {
// cool
} else {
// handle the failure, but there's no error information available
}
But Swift's error handling system also provides a way to "force try" with try!
:
let result = try! someThrowingFunc()
The concepts explained in this post also apply here: if an error is thrown, the application will crash.
You should only ever use try!
if you can prove that its result will never fail in your context - and this is very rare.
Most of the time you will use the complete Do-Try-Catch system - and the optional one, try?
, in the rare cases where handling the error is not important.
Resources
- Apple documentation on Swift Optionals
- When to use and when not to use implicitly unwrapped optionals
- Learn how to debug an iOS app crash
63
Personally, I would like to thank you for putting in the effort to write all of this. I feel like this will certainly be helpful to beginners and experts alike using swift.
– Pranav Wadhwa
Jun 6 '16 at 1:27
12
I'm glad you found it helpful. This answer is community wiki, so it's a collaboration between many people (7, so far)!
– jtbandes
Jun 6 '16 at 4:44
This error is intermittent in my case. Any suggestions? Code in stackoverflow.com/questions/50933681/…
– py_ios_dev
Jun 19 at 17:12
Perhaps it's time to update this answer to usecompactMap()
instead offlatMap()
.
– Nicolas Miari
Sep 19 at 5:48
add a comment |
This answer is community wiki. If you feel it could be made better, feel free to edit it!
Background: What’s an Optional?
In Swift, Optional
is a generic type that can contain a value (of any kind), or no value at all.
In many other programming languages, a particular "sentinel" value is often used to indicate a lack of a value. In Objective-C, for example, nil
(the null pointer) indicates the lack of an object. But this gets more tricky when working with primitive types — should -1
be used to indicate the absence of an integer, or perhaps INT_MIN
, or some other integer? If any particular value is chosen to mean "no integer", that means it can no longer be treated as a valid value.
Swift is a type-safe language, which means the language helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake.
In Swift, any type can be made optional. An optional value can take on any value from the original type, or the special value nil
.
Optionals are defined with a ?
suffix on the type:
var anInt: Int = 42
var anOptionalInt: Int? = 42
var anotherOptionalInt: Int? // `nil` is the default when no value is provided
The lack of a value in an optional is indicated by nil
:
anOptionalInt = nil
(Note that this nil
is not the same as the nil
in Objective-C. In Objective-C, nil
is the absence of a valid object pointer; in Swift, Optionals are not restricted to objects/reference types. Optional behaves similarly to Haskell's Maybe.)
Why did I get “fatal error: unexpectedly found nil while unwrapping an Optional value”?
In order to access an optional’s value (if it has one at all), you need to unwrap it. An optional value can be unwrapped safely or forcibly. If you force-unwrap an optional, and it didn't have a value, your program will crash with the above message.
Xcode will show you the crash by highlighting a line of code. The problem occurs on this line.
This crash can occur with two different kinds of force-unwrap:
1. Explicit Force Unwrapping
This is done with the !
operator on an optional. For example:
let anOptionalString: String?
print(anOptionalString!) // <- CRASH
As anOptionalString
is nil
here, you will get a crash on the line where you force unwrap it.
2. Implicitly Unwrapped Optionals
These are defined with a !
, rather than a ?
after the type.
var optionalDouble: Double! // this value is implicitly unwrapped wherever it's used
These optionals are assumed to contain a value. Therefore whenever you access an implicitly unwrapped optional, it will automatically be force unwrapped for you. If it doesn’t contain a value, it will crash.
print(optionalDouble) // <- CRASH
In order to work out which variable caused the crash, you can hold ⌥ while clicking to show the definition, where you might find the optional type.
IBOutlets, in particular, are usually implicitly unwrapped optionals. This is because your xib or storyboard will link up the outlets at runtime, after initialization. You should therefore ensure that you’re not accessing outlets before they're loaded in. You also should check that the connections are correct in your storyboard/xib file, otherwise the values will be nil
at runtime, and therefore crash when they are implicitly unwrapped.
When should I ever force unwrap an Optional?
Explicit Force Unwrapping
As a general rule, you should never explicitly force unwrap an optional with the !
operator. There may be cases where using !
is acceptable – but you should only ever be using it if you are 100% sure that the optional contains a value.
While there may be an occasion where you can use force unwrapping, as you know for a fact that an optional contains a value – there is not a single place where you cannot safely unwrap that optional instead.
Implicitly Unwrapped Optionals
These variables are designed so that you can defer their assignment until later in your code. It is your responsibility to ensure they have a value before you access them. However, because they involve force unwrapping, they are still inherently unsafe – as they assume your value is non-nil, even though assigning nil is valid.
You should only be using implicitly unwrapped optionals as a last resort. If you can use a lazy variable, or provide a default value for a variable – you should do so instead of using an implicitly unwrapped optional.
However, there are a few scenarios where implicitly unwrapped optionals are beneficial, and you are still able to use various ways of safely unwrapping them as listed below – but you should always use them with due caution.
How can I safely deal with Optionals?
The simplest way to check whether an optional contains a value, is to compare it to nil
.
if anOptionalInt != nil {
print("Contains a value!")
} else {
print("Doesn’t contain a value.")
}
However, 99.9% of the time when working with optionals, you’ll actually want to access the value it contains, if it contains one at all. To do this, you can use Optional Binding.
Optional Binding
Optional Binding allows you to check if an optional contains a value – and allows you to assign the unwrapped value to a new variable or constant. It uses the syntax if let x = anOptional {...}
or if var x = anOptional {...}
, depending if you need to modify the value of the new variable after binding it.
For example:
if let number = anOptionalInt {
print("Contains a value! It is (number)!")
} else {
print("Doesn’t contain a number")
}
What this does is first check that the optional contains a value. If it does, then the ‘unwrapped’ value is assigned to a new variable (number
) – which you can then freely use as if it were non-optional. If the optional doesn’t contain a value, then the else clause will be invoked, as you would expect.
What’s neat about optional binding, is you can unwrap multiple optionals at the same time. You can just separate the statements with a comma. The statement will succeed if all the optionals were unwrapped.
var anOptionalInt : Int?
var anOptionalString : String?
if let number = anOptionalInt, let text = anOptionalString {
print("anOptionalInt contains a value: (number). And so does anOptionalString, it’s: (text)")
} else {
print("One or more of the optionals don’t contain a value")
}
Another neat trick is that you can also use commas to check for a certain condition on the value, after unwrapping it.
if let number = anOptionalInt, number > 0 {
print("anOptionalInt contains a value: (number), and it’s greater than zero!")
}
The only catch with using optional binding within an if statement, is that you can only access the unwrapped value from within the scope of the statement. If you need access to the value from outside of the scope of the statement, you can use a guard statement.
A guard statement allows you to define a condition for success – and the current scope will only continue executing if that condition is met. They are defined with the syntax guard condition else {...}
.
So, to use them with an optional binding, you can do this:
guard let number = anOptionalInt else {
return
}
(Note that within the guard body, you must use one of the control transfer statements in order to exit the scope of the currently executing code).
If anOptionalInt
contains a value, it will be unwrapped and assigned to the new number
constant. The code after the guard will then continue executing. If it doesn’t contain a value – the guard will execute the code within the brackets, which will lead to transfer of control, so that the code immediately after will not be executed.
The real neat thing about guard statements is the unwrapped value is now available to use in code that follows the statement (as we know that future code can only execute if the optional has a value). This is a great for eliminating ‘pyramids of doom’ created by nesting multiple if statements.
For example:
guard let number = anOptionalInt else {
return
}
print("anOptionalInt contains a value, and it’s: (number)!")
Guards also support the same neat tricks that the if statement supported, such as unwrapping multiple optionals at the same time and using the where
clause.
Whether you use an if or guard statement completely depends on whether any future code requires the optional to contain a value.
Nil Coalescing Operator
The Nil Coalescing Operator is a nifty shorthand version of the ternary conditional operator, primarily designed to convert optionals to non-optionals. It has the syntax a ?? b
, where a
is an optional type and b
is the same type as a
(although usually non-optional).
It essentially lets you say “If a
contains a value, unwrap it. If it doesn’t then return b
instead”. For example, you could use it like this:
let number = anOptionalInt ?? 0
This will define a number
constant of Int
type, that will either contain the value of anOptionalInt
, if it contains a value, or 0
otherwise.
It’s just shorthand for:
let number = anOptionalInt != nil ? anOptionalInt! : 0
Optional Chaining
You can use Optional Chaining in order to call a method or access a property on an optional. This is simply done by suffixing the variable name with a ?
when using it.
For example, say we have a variable foo
, of type an optional Foo
instance.
var foo : Foo?
If we wanted to call a method on foo
that doesn’t return anything, we can simply do:
foo?.doSomethingInteresting()
If foo
contains a value, this method will be called on it. If it doesn’t, nothing bad will happen – the code will simply continue executing.
(This is similar behaviour to sending messages to nil
in Objective-C)
This can therefore also be used to set properties as well as call methods. For example:
foo?.bar = Bar()
Again, nothing bad will happen here if foo
is nil
. Your code will simply continue executing.
Another neat trick that optional chaining lets you do is check whether setting a property or calling a method was successful. You can do this by comparing the return value to nil
.
(This is because an optional value will return Void?
rather than Void
on a method that doesn’t return anything)
For example:
if (foo?.bar = Bar()) != nil {
print("bar was set successfully")
} else {
print("bar wasn’t set successfully")
}
However, things become a little bit more tricky when trying to access properties or call methods that return a value. Because foo
is optional, anything returned from it will also be optional. To deal with this, you can either unwrap the optionals that get returned using one of the above methods – or unwrap foo
itself before accessing methods or calling methods that return values.
Also, as the name suggests, you can ‘chain’ these statements together. This means that if foo
has an optional property baz
, which has a property qux
– you could write the following:
let optionalQux = foo?.baz?.qux
Again, because foo
and baz
are optional, the value returned from qux
will always be an optional regardless of whether qux
itself is optional.
map
and flatMap
An often underused feature with optionals is the ability to use the map
and flatMap
functions. These allow you to apply non-optional transforms to optional variables. If an optional has a value, you can apply a given transformation to it. If it doesn’t have a value, it will remain nil
.
For example, let’s say you have an optional string:
let anOptionalString:String?
By applying the map
function to it – we can use the stringByAppendingString
function in order to concatenate it to another string.
Because stringByAppendingString
takes a non-optional string argument, we cannot input our optional string directly. However, by using map
, we can use allow stringByAppendingString
to be used if anOptionalString
has a value.
For example:
var anOptionalString:String? = "bar"
anOptionalString = anOptionalString.map {unwrappedString in
return "foo".stringByAppendingString(unwrappedString)
}
print(anOptionalString) // Optional("foobar")
However, if anOptionalString
doesn’t have a value, map
will return nil
. For example:
var anOptionalString:String?
anOptionalString = anOptionalString.map {unwrappedString in
return "foo".stringByAppendingString(unwrappedString)
}
print(anOptionalString) // nil
flatMap
works similarly to map
, except it allows you to return another optional from within the closure body. This means you can input an optional into a process that requires a non-optional input, but can output an optional itself.
try!
Swift's error handling system can be safely used with Do-Try-Catch:
do {
let result = try someThrowingFunc()
} catch {
print(error)
}
If someThrowingFunc()
throws an error, the error will be safely caught in the catch
block.
The error
constant you see in the catch
block has not been declared by us - it's automatically generated by catch
.
You can also declare error
yourself, it has the advantage of being able to cast it to a useful format, for example:
do {
let result = try someThrowingFunc()
} catch let error as NSError {
print(error.debugDescription)
}
Using try
this way is the proper way to try, catch and handle errors coming from throwing functions.
There's also try?
which absorbs the error:
if let result = try? someThrowingFunc() {
// cool
} else {
// handle the failure, but there's no error information available
}
But Swift's error handling system also provides a way to "force try" with try!
:
let result = try! someThrowingFunc()
The concepts explained in this post also apply here: if an error is thrown, the application will crash.
You should only ever use try!
if you can prove that its result will never fail in your context - and this is very rare.
Most of the time you will use the complete Do-Try-Catch system - and the optional one, try?
, in the rare cases where handling the error is not important.
Resources
- Apple documentation on Swift Optionals
- When to use and when not to use implicitly unwrapped optionals
- Learn how to debug an iOS app crash
This answer is community wiki. If you feel it could be made better, feel free to edit it!
Background: What’s an Optional?
In Swift, Optional
is a generic type that can contain a value (of any kind), or no value at all.
In many other programming languages, a particular "sentinel" value is often used to indicate a lack of a value. In Objective-C, for example, nil
(the null pointer) indicates the lack of an object. But this gets more tricky when working with primitive types — should -1
be used to indicate the absence of an integer, or perhaps INT_MIN
, or some other integer? If any particular value is chosen to mean "no integer", that means it can no longer be treated as a valid value.
Swift is a type-safe language, which means the language helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake.
In Swift, any type can be made optional. An optional value can take on any value from the original type, or the special value nil
.
Optionals are defined with a ?
suffix on the type:
var anInt: Int = 42
var anOptionalInt: Int? = 42
var anotherOptionalInt: Int? // `nil` is the default when no value is provided
The lack of a value in an optional is indicated by nil
:
anOptionalInt = nil
(Note that this nil
is not the same as the nil
in Objective-C. In Objective-C, nil
is the absence of a valid object pointer; in Swift, Optionals are not restricted to objects/reference types. Optional behaves similarly to Haskell's Maybe.)
Why did I get “fatal error: unexpectedly found nil while unwrapping an Optional value”?
In order to access an optional’s value (if it has one at all), you need to unwrap it. An optional value can be unwrapped safely or forcibly. If you force-unwrap an optional, and it didn't have a value, your program will crash with the above message.
Xcode will show you the crash by highlighting a line of code. The problem occurs on this line.
This crash can occur with two different kinds of force-unwrap:
1. Explicit Force Unwrapping
This is done with the !
operator on an optional. For example:
let anOptionalString: String?
print(anOptionalString!) // <- CRASH
As anOptionalString
is nil
here, you will get a crash on the line where you force unwrap it.
2. Implicitly Unwrapped Optionals
These are defined with a !
, rather than a ?
after the type.
var optionalDouble: Double! // this value is implicitly unwrapped wherever it's used
These optionals are assumed to contain a value. Therefore whenever you access an implicitly unwrapped optional, it will automatically be force unwrapped for you. If it doesn’t contain a value, it will crash.
print(optionalDouble) // <- CRASH
In order to work out which variable caused the crash, you can hold ⌥ while clicking to show the definition, where you might find the optional type.
IBOutlets, in particular, are usually implicitly unwrapped optionals. This is because your xib or storyboard will link up the outlets at runtime, after initialization. You should therefore ensure that you’re not accessing outlets before they're loaded in. You also should check that the connections are correct in your storyboard/xib file, otherwise the values will be nil
at runtime, and therefore crash when they are implicitly unwrapped.
When should I ever force unwrap an Optional?
Explicit Force Unwrapping
As a general rule, you should never explicitly force unwrap an optional with the !
operator. There may be cases where using !
is acceptable – but you should only ever be using it if you are 100% sure that the optional contains a value.
While there may be an occasion where you can use force unwrapping, as you know for a fact that an optional contains a value – there is not a single place where you cannot safely unwrap that optional instead.
Implicitly Unwrapped Optionals
These variables are designed so that you can defer their assignment until later in your code. It is your responsibility to ensure they have a value before you access them. However, because they involve force unwrapping, they are still inherently unsafe – as they assume your value is non-nil, even though assigning nil is valid.
You should only be using implicitly unwrapped optionals as a last resort. If you can use a lazy variable, or provide a default value for a variable – you should do so instead of using an implicitly unwrapped optional.
However, there are a few scenarios where implicitly unwrapped optionals are beneficial, and you are still able to use various ways of safely unwrapping them as listed below – but you should always use them with due caution.
How can I safely deal with Optionals?
The simplest way to check whether an optional contains a value, is to compare it to nil
.
if anOptionalInt != nil {
print("Contains a value!")
} else {
print("Doesn’t contain a value.")
}
However, 99.9% of the time when working with optionals, you’ll actually want to access the value it contains, if it contains one at all. To do this, you can use Optional Binding.
Optional Binding
Optional Binding allows you to check if an optional contains a value – and allows you to assign the unwrapped value to a new variable or constant. It uses the syntax if let x = anOptional {...}
or if var x = anOptional {...}
, depending if you need to modify the value of the new variable after binding it.
For example:
if let number = anOptionalInt {
print("Contains a value! It is (number)!")
} else {
print("Doesn’t contain a number")
}
What this does is first check that the optional contains a value. If it does, then the ‘unwrapped’ value is assigned to a new variable (number
) – which you can then freely use as if it were non-optional. If the optional doesn’t contain a value, then the else clause will be invoked, as you would expect.
What’s neat about optional binding, is you can unwrap multiple optionals at the same time. You can just separate the statements with a comma. The statement will succeed if all the optionals were unwrapped.
var anOptionalInt : Int?
var anOptionalString : String?
if let number = anOptionalInt, let text = anOptionalString {
print("anOptionalInt contains a value: (number). And so does anOptionalString, it’s: (text)")
} else {
print("One or more of the optionals don’t contain a value")
}
Another neat trick is that you can also use commas to check for a certain condition on the value, after unwrapping it.
if let number = anOptionalInt, number > 0 {
print("anOptionalInt contains a value: (number), and it’s greater than zero!")
}
The only catch with using optional binding within an if statement, is that you can only access the unwrapped value from within the scope of the statement. If you need access to the value from outside of the scope of the statement, you can use a guard statement.
A guard statement allows you to define a condition for success – and the current scope will only continue executing if that condition is met. They are defined with the syntax guard condition else {...}
.
So, to use them with an optional binding, you can do this:
guard let number = anOptionalInt else {
return
}
(Note that within the guard body, you must use one of the control transfer statements in order to exit the scope of the currently executing code).
If anOptionalInt
contains a value, it will be unwrapped and assigned to the new number
constant. The code after the guard will then continue executing. If it doesn’t contain a value – the guard will execute the code within the brackets, which will lead to transfer of control, so that the code immediately after will not be executed.
The real neat thing about guard statements is the unwrapped value is now available to use in code that follows the statement (as we know that future code can only execute if the optional has a value). This is a great for eliminating ‘pyramids of doom’ created by nesting multiple if statements.
For example:
guard let number = anOptionalInt else {
return
}
print("anOptionalInt contains a value, and it’s: (number)!")
Guards also support the same neat tricks that the if statement supported, such as unwrapping multiple optionals at the same time and using the where
clause.
Whether you use an if or guard statement completely depends on whether any future code requires the optional to contain a value.
Nil Coalescing Operator
The Nil Coalescing Operator is a nifty shorthand version of the ternary conditional operator, primarily designed to convert optionals to non-optionals. It has the syntax a ?? b
, where a
is an optional type and b
is the same type as a
(although usually non-optional).
It essentially lets you say “If a
contains a value, unwrap it. If it doesn’t then return b
instead”. For example, you could use it like this:
let number = anOptionalInt ?? 0
This will define a number
constant of Int
type, that will either contain the value of anOptionalInt
, if it contains a value, or 0
otherwise.
It’s just shorthand for:
let number = anOptionalInt != nil ? anOptionalInt! : 0
Optional Chaining
You can use Optional Chaining in order to call a method or access a property on an optional. This is simply done by suffixing the variable name with a ?
when using it.
For example, say we have a variable foo
, of type an optional Foo
instance.
var foo : Foo?
If we wanted to call a method on foo
that doesn’t return anything, we can simply do:
foo?.doSomethingInteresting()
If foo
contains a value, this method will be called on it. If it doesn’t, nothing bad will happen – the code will simply continue executing.
(This is similar behaviour to sending messages to nil
in Objective-C)
This can therefore also be used to set properties as well as call methods. For example:
foo?.bar = Bar()
Again, nothing bad will happen here if foo
is nil
. Your code will simply continue executing.
Another neat trick that optional chaining lets you do is check whether setting a property or calling a method was successful. You can do this by comparing the return value to nil
.
(This is because an optional value will return Void?
rather than Void
on a method that doesn’t return anything)
For example:
if (foo?.bar = Bar()) != nil {
print("bar was set successfully")
} else {
print("bar wasn’t set successfully")
}
However, things become a little bit more tricky when trying to access properties or call methods that return a value. Because foo
is optional, anything returned from it will also be optional. To deal with this, you can either unwrap the optionals that get returned using one of the above methods – or unwrap foo
itself before accessing methods or calling methods that return values.
Also, as the name suggests, you can ‘chain’ these statements together. This means that if foo
has an optional property baz
, which has a property qux
– you could write the following:
let optionalQux = foo?.baz?.qux
Again, because foo
and baz
are optional, the value returned from qux
will always be an optional regardless of whether qux
itself is optional.
map
and flatMap
An often underused feature with optionals is the ability to use the map
and flatMap
functions. These allow you to apply non-optional transforms to optional variables. If an optional has a value, you can apply a given transformation to it. If it doesn’t have a value, it will remain nil
.
For example, let’s say you have an optional string:
let anOptionalString:String?
By applying the map
function to it – we can use the stringByAppendingString
function in order to concatenate it to another string.
Because stringByAppendingString
takes a non-optional string argument, we cannot input our optional string directly. However, by using map
, we can use allow stringByAppendingString
to be used if anOptionalString
has a value.
For example:
var anOptionalString:String? = "bar"
anOptionalString = anOptionalString.map {unwrappedString in
return "foo".stringByAppendingString(unwrappedString)
}
print(anOptionalString) // Optional("foobar")
However, if anOptionalString
doesn’t have a value, map
will return nil
. For example:
var anOptionalString:String?
anOptionalString = anOptionalString.map {unwrappedString in
return "foo".stringByAppendingString(unwrappedString)
}
print(anOptionalString) // nil
flatMap
works similarly to map
, except it allows you to return another optional from within the closure body. This means you can input an optional into a process that requires a non-optional input, but can output an optional itself.
try!
Swift's error handling system can be safely used with Do-Try-Catch:
do {
let result = try someThrowingFunc()
} catch {
print(error)
}
If someThrowingFunc()
throws an error, the error will be safely caught in the catch
block.
The error
constant you see in the catch
block has not been declared by us - it's automatically generated by catch
.
You can also declare error
yourself, it has the advantage of being able to cast it to a useful format, for example:
do {
let result = try someThrowingFunc()
} catch let error as NSError {
print(error.debugDescription)
}
Using try
this way is the proper way to try, catch and handle errors coming from throwing functions.
There's also try?
which absorbs the error:
if let result = try? someThrowingFunc() {
// cool
} else {
// handle the failure, but there's no error information available
}
But Swift's error handling system also provides a way to "force try" with try!
:
let result = try! someThrowingFunc()
The concepts explained in this post also apply here: if an error is thrown, the application will crash.
You should only ever use try!
if you can prove that its result will never fail in your context - and this is very rare.
Most of the time you will use the complete Do-Try-Catch system - and the optional one, try?
, in the rare cases where handling the error is not important.
Resources
- Apple documentation on Swift Optionals
- When to use and when not to use implicitly unwrapped optionals
- Learn how to debug an iOS app crash
edited Jul 3 at 17:57
community wiki
28 revs, 12 users 63%
Hamish
63
Personally, I would like to thank you for putting in the effort to write all of this. I feel like this will certainly be helpful to beginners and experts alike using swift.
– Pranav Wadhwa
Jun 6 '16 at 1:27
12
I'm glad you found it helpful. This answer is community wiki, so it's a collaboration between many people (7, so far)!
– jtbandes
Jun 6 '16 at 4:44
This error is intermittent in my case. Any suggestions? Code in stackoverflow.com/questions/50933681/…
– py_ios_dev
Jun 19 at 17:12
Perhaps it's time to update this answer to usecompactMap()
instead offlatMap()
.
– Nicolas Miari
Sep 19 at 5:48
add a comment |
63
Personally, I would like to thank you for putting in the effort to write all of this. I feel like this will certainly be helpful to beginners and experts alike using swift.
– Pranav Wadhwa
Jun 6 '16 at 1:27
12
I'm glad you found it helpful. This answer is community wiki, so it's a collaboration between many people (7, so far)!
– jtbandes
Jun 6 '16 at 4:44
This error is intermittent in my case. Any suggestions? Code in stackoverflow.com/questions/50933681/…
– py_ios_dev
Jun 19 at 17:12
Perhaps it's time to update this answer to usecompactMap()
instead offlatMap()
.
– Nicolas Miari
Sep 19 at 5:48
63
63
Personally, I would like to thank you for putting in the effort to write all of this. I feel like this will certainly be helpful to beginners and experts alike using swift.
– Pranav Wadhwa
Jun 6 '16 at 1:27
Personally, I would like to thank you for putting in the effort to write all of this. I feel like this will certainly be helpful to beginners and experts alike using swift.
– Pranav Wadhwa
Jun 6 '16 at 1:27
12
12
I'm glad you found it helpful. This answer is community wiki, so it's a collaboration between many people (7, so far)!
– jtbandes
Jun 6 '16 at 4:44
I'm glad you found it helpful. This answer is community wiki, so it's a collaboration between many people (7, so far)!
– jtbandes
Jun 6 '16 at 4:44
This error is intermittent in my case. Any suggestions? Code in stackoverflow.com/questions/50933681/…
– py_ios_dev
Jun 19 at 17:12
This error is intermittent in my case. Any suggestions? Code in stackoverflow.com/questions/50933681/…
– py_ios_dev
Jun 19 at 17:12
Perhaps it's time to update this answer to use
compactMap()
instead of flatMap()
.– Nicolas Miari
Sep 19 at 5:48
Perhaps it's time to update this answer to use
compactMap()
instead of flatMap()
.– Nicolas Miari
Sep 19 at 5:48
add a comment |
TL;DR answer
With very few exceptions, this rule is golden:
Avoid use of !
Declare variable optional (?
), not implicitly unwrapped optionals (IUO) (!
)
In other words, rather use:var nameOfDaughter: String?
Instead of:var nameOfDaughter: String!
Unwrap optional variable using if let
or guard let
Either unwrap variable like this:
if let nameOfDaughter = nameOfDaughter {
print("My daughters name is: (nameOfDaughter)")
}
Or like this:
guard let nameOfDaughter = nameOfDaughter else { return }
print("My daughters name is: (nameOfDaughter)")
This answer was intended to be concise, for full comprehension read accepted answer
add a comment |
TL;DR answer
With very few exceptions, this rule is golden:
Avoid use of !
Declare variable optional (?
), not implicitly unwrapped optionals (IUO) (!
)
In other words, rather use:var nameOfDaughter: String?
Instead of:var nameOfDaughter: String!
Unwrap optional variable using if let
or guard let
Either unwrap variable like this:
if let nameOfDaughter = nameOfDaughter {
print("My daughters name is: (nameOfDaughter)")
}
Or like this:
guard let nameOfDaughter = nameOfDaughter else { return }
print("My daughters name is: (nameOfDaughter)")
This answer was intended to be concise, for full comprehension read accepted answer
add a comment |
TL;DR answer
With very few exceptions, this rule is golden:
Avoid use of !
Declare variable optional (?
), not implicitly unwrapped optionals (IUO) (!
)
In other words, rather use:var nameOfDaughter: String?
Instead of:var nameOfDaughter: String!
Unwrap optional variable using if let
or guard let
Either unwrap variable like this:
if let nameOfDaughter = nameOfDaughter {
print("My daughters name is: (nameOfDaughter)")
}
Or like this:
guard let nameOfDaughter = nameOfDaughter else { return }
print("My daughters name is: (nameOfDaughter)")
This answer was intended to be concise, for full comprehension read accepted answer
TL;DR answer
With very few exceptions, this rule is golden:
Avoid use of !
Declare variable optional (?
), not implicitly unwrapped optionals (IUO) (!
)
In other words, rather use:var nameOfDaughter: String?
Instead of:var nameOfDaughter: String!
Unwrap optional variable using if let
or guard let
Either unwrap variable like this:
if let nameOfDaughter = nameOfDaughter {
print("My daughters name is: (nameOfDaughter)")
}
Or like this:
guard let nameOfDaughter = nameOfDaughter else { return }
print("My daughters name is: (nameOfDaughter)")
This answer was intended to be concise, for full comprehension read accepted answer
edited Jul 25 at 9:59
community wiki
6 revs, 3 users 91%
Sajjon
add a comment |
add a comment |
This question comes up ALL THE TIME on SO. It's one of the first things that new Swift developers struggle with.
Background:
Swift uses the concept of "Optionals" to deal with values that could contain a value, or not. In other languages like C, you might store a value of 0 in a variable to indicate that it contains no value. However, what if 0 is a valid value? Then you might use -1. What if -1 is a valid value? And so on.
Swift optionals let you set up a variable of any type to contain either a valid value, or no value.
You put a question mark after the type when you declare a variable to mean (type x, or no value).
An optional is actually a container than contains either a variable of a given type, or nothing.
An optional needs to be "unwrapped" in order to fetch the value inside.
The "!" operator is a "force unwrap" operator. It says "trust me. I know what I am doing. I guarantee that when this code runs, the variable will not contain nil." If you are wrong, you crash.
Unless you really do know what you are doing, avoid the "!" force unwrap operator. It is probably the largest source of crashes for beginning Swift programmers.
How to deal with optionals:
There are lots of other ways of dealing with optionals that are safer. Here are some (not an exhaustive list)
You can use "optional binding" or "if let" to say "if this optional contains a value, save that value into a new, non-optional variable. If the optional does not contain a value, skip the body of this if statement".
Here is an example of optional binding with our foo
optional:
if let newFoo = foo //If let is called optional binding. {
print("foo is not nil")
} else {
print("foo is nil")
}
Note that the variable you define when you use optional biding only exists (is only "in scope") in the body of the if statement.
Alternately, you could use a guard statement, which lets you exit your function if the variable is nil:
func aFunc(foo: Int?) {
guard let newFoo = input else { return }
//For the rest of the function newFoo is a non-optional var
}
Guard statements were added in Swift 2. Guard lets you preserve the "golden path" through your code, and avoid ever-increasing levels of nested ifs that sometimes result from using "if let" optional binding.
There is also a construct called the "nil coalescing operator". It takes the form "optional_var ?? replacement_val". It returns a non-optional variable with the same type as the data contained in the optional. If the optional contains nil, it returns the value of the expression after the "??" symbol.
So you could use code like this:
let newFoo = foo ?? "nil" // "??" is the nil coalescing operator
print("foo = (newFoo)")
You could also use try/catch or guard error handling, but generally one of the other techniques above is cleaner.
EDIT:
Another, slightly more subtle gotcha with optionals is "implicitly unwrapped optionals. When we declare foo, we could say:
var foo: String!
In that case foo is still an optional, but you don't have to unwrap it to reference it. That means any time you try to reference foo, you crash if it's nil.
So this code:
var foo: String!
let upperFoo = foo.capitalizedString
Will crash on reference to foo's capitalizedString property even though we're not force-unwrapping foo. the print looks fine, but it's not.
Thus you want to be really careful with implicitly unwrapped optionals. (and perhaps even avoid them completely until you have a solid understanding of optionals.)
Bottom line: When you are first learning Swift, pretend the "!" character is not part of the language. It's likely to get you into trouble.
7
You should consider making this a public wiki.
– vacawama
Feb 28 '16 at 14:42
3
Edit your answer, and below the edit box on the right is a community wiki checkbox. You will no longer get rep for the answer, but I know this isn't a blatant rep grab anyway.
– vacawama
Feb 28 '16 at 14:49
2
meta.stackexchange.com/q/11740/200104
– vacawama
Feb 28 '16 at 14:55
6
Given that this question is asked a million times on the site, if I were going to take the time to post a self-answered question as the canonical answer to the question, I'd hope that the answer is far more complete than this. There's nothing aboutguard
clauses. There's nothing about use ofif var
which is just as valid a construct asif let
. There's nothing aboutwhere
clauses which I feel is worth mention when we're talking aboutif let
binding (it removes a whole layer of nesting in many cases). There's nothing about optional chaining.
– nhgrif
Feb 28 '16 at 22:00
6
And when you mention implicitly unwrapped optionals, you don't even mention that you can use all of the aforementioned optional tricks to safely unwrap implicitly unwrapped optionals. We also don't cover unwrapping multiple options in the same clause.
– nhgrif
Feb 28 '16 at 22:01
|
show 4 more comments
This question comes up ALL THE TIME on SO. It's one of the first things that new Swift developers struggle with.
Background:
Swift uses the concept of "Optionals" to deal with values that could contain a value, or not. In other languages like C, you might store a value of 0 in a variable to indicate that it contains no value. However, what if 0 is a valid value? Then you might use -1. What if -1 is a valid value? And so on.
Swift optionals let you set up a variable of any type to contain either a valid value, or no value.
You put a question mark after the type when you declare a variable to mean (type x, or no value).
An optional is actually a container than contains either a variable of a given type, or nothing.
An optional needs to be "unwrapped" in order to fetch the value inside.
The "!" operator is a "force unwrap" operator. It says "trust me. I know what I am doing. I guarantee that when this code runs, the variable will not contain nil." If you are wrong, you crash.
Unless you really do know what you are doing, avoid the "!" force unwrap operator. It is probably the largest source of crashes for beginning Swift programmers.
How to deal with optionals:
There are lots of other ways of dealing with optionals that are safer. Here are some (not an exhaustive list)
You can use "optional binding" or "if let" to say "if this optional contains a value, save that value into a new, non-optional variable. If the optional does not contain a value, skip the body of this if statement".
Here is an example of optional binding with our foo
optional:
if let newFoo = foo //If let is called optional binding. {
print("foo is not nil")
} else {
print("foo is nil")
}
Note that the variable you define when you use optional biding only exists (is only "in scope") in the body of the if statement.
Alternately, you could use a guard statement, which lets you exit your function if the variable is nil:
func aFunc(foo: Int?) {
guard let newFoo = input else { return }
//For the rest of the function newFoo is a non-optional var
}
Guard statements were added in Swift 2. Guard lets you preserve the "golden path" through your code, and avoid ever-increasing levels of nested ifs that sometimes result from using "if let" optional binding.
There is also a construct called the "nil coalescing operator". It takes the form "optional_var ?? replacement_val". It returns a non-optional variable with the same type as the data contained in the optional. If the optional contains nil, it returns the value of the expression after the "??" symbol.
So you could use code like this:
let newFoo = foo ?? "nil" // "??" is the nil coalescing operator
print("foo = (newFoo)")
You could also use try/catch or guard error handling, but generally one of the other techniques above is cleaner.
EDIT:
Another, slightly more subtle gotcha with optionals is "implicitly unwrapped optionals. When we declare foo, we could say:
var foo: String!
In that case foo is still an optional, but you don't have to unwrap it to reference it. That means any time you try to reference foo, you crash if it's nil.
So this code:
var foo: String!
let upperFoo = foo.capitalizedString
Will crash on reference to foo's capitalizedString property even though we're not force-unwrapping foo. the print looks fine, but it's not.
Thus you want to be really careful with implicitly unwrapped optionals. (and perhaps even avoid them completely until you have a solid understanding of optionals.)
Bottom line: When you are first learning Swift, pretend the "!" character is not part of the language. It's likely to get you into trouble.
7
You should consider making this a public wiki.
– vacawama
Feb 28 '16 at 14:42
3
Edit your answer, and below the edit box on the right is a community wiki checkbox. You will no longer get rep for the answer, but I know this isn't a blatant rep grab anyway.
– vacawama
Feb 28 '16 at 14:49
2
meta.stackexchange.com/q/11740/200104
– vacawama
Feb 28 '16 at 14:55
6
Given that this question is asked a million times on the site, if I were going to take the time to post a self-answered question as the canonical answer to the question, I'd hope that the answer is far more complete than this. There's nothing aboutguard
clauses. There's nothing about use ofif var
which is just as valid a construct asif let
. There's nothing aboutwhere
clauses which I feel is worth mention when we're talking aboutif let
binding (it removes a whole layer of nesting in many cases). There's nothing about optional chaining.
– nhgrif
Feb 28 '16 at 22:00
6
And when you mention implicitly unwrapped optionals, you don't even mention that you can use all of the aforementioned optional tricks to safely unwrap implicitly unwrapped optionals. We also don't cover unwrapping multiple options in the same clause.
– nhgrif
Feb 28 '16 at 22:01
|
show 4 more comments
This question comes up ALL THE TIME on SO. It's one of the first things that new Swift developers struggle with.
Background:
Swift uses the concept of "Optionals" to deal with values that could contain a value, or not. In other languages like C, you might store a value of 0 in a variable to indicate that it contains no value. However, what if 0 is a valid value? Then you might use -1. What if -1 is a valid value? And so on.
Swift optionals let you set up a variable of any type to contain either a valid value, or no value.
You put a question mark after the type when you declare a variable to mean (type x, or no value).
An optional is actually a container than contains either a variable of a given type, or nothing.
An optional needs to be "unwrapped" in order to fetch the value inside.
The "!" operator is a "force unwrap" operator. It says "trust me. I know what I am doing. I guarantee that when this code runs, the variable will not contain nil." If you are wrong, you crash.
Unless you really do know what you are doing, avoid the "!" force unwrap operator. It is probably the largest source of crashes for beginning Swift programmers.
How to deal with optionals:
There are lots of other ways of dealing with optionals that are safer. Here are some (not an exhaustive list)
You can use "optional binding" or "if let" to say "if this optional contains a value, save that value into a new, non-optional variable. If the optional does not contain a value, skip the body of this if statement".
Here is an example of optional binding with our foo
optional:
if let newFoo = foo //If let is called optional binding. {
print("foo is not nil")
} else {
print("foo is nil")
}
Note that the variable you define when you use optional biding only exists (is only "in scope") in the body of the if statement.
Alternately, you could use a guard statement, which lets you exit your function if the variable is nil:
func aFunc(foo: Int?) {
guard let newFoo = input else { return }
//For the rest of the function newFoo is a non-optional var
}
Guard statements were added in Swift 2. Guard lets you preserve the "golden path" through your code, and avoid ever-increasing levels of nested ifs that sometimes result from using "if let" optional binding.
There is also a construct called the "nil coalescing operator". It takes the form "optional_var ?? replacement_val". It returns a non-optional variable with the same type as the data contained in the optional. If the optional contains nil, it returns the value of the expression after the "??" symbol.
So you could use code like this:
let newFoo = foo ?? "nil" // "??" is the nil coalescing operator
print("foo = (newFoo)")
You could also use try/catch or guard error handling, but generally one of the other techniques above is cleaner.
EDIT:
Another, slightly more subtle gotcha with optionals is "implicitly unwrapped optionals. When we declare foo, we could say:
var foo: String!
In that case foo is still an optional, but you don't have to unwrap it to reference it. That means any time you try to reference foo, you crash if it's nil.
So this code:
var foo: String!
let upperFoo = foo.capitalizedString
Will crash on reference to foo's capitalizedString property even though we're not force-unwrapping foo. the print looks fine, but it's not.
Thus you want to be really careful with implicitly unwrapped optionals. (and perhaps even avoid them completely until you have a solid understanding of optionals.)
Bottom line: When you are first learning Swift, pretend the "!" character is not part of the language. It's likely to get you into trouble.
This question comes up ALL THE TIME on SO. It's one of the first things that new Swift developers struggle with.
Background:
Swift uses the concept of "Optionals" to deal with values that could contain a value, or not. In other languages like C, you might store a value of 0 in a variable to indicate that it contains no value. However, what if 0 is a valid value? Then you might use -1. What if -1 is a valid value? And so on.
Swift optionals let you set up a variable of any type to contain either a valid value, or no value.
You put a question mark after the type when you declare a variable to mean (type x, or no value).
An optional is actually a container than contains either a variable of a given type, or nothing.
An optional needs to be "unwrapped" in order to fetch the value inside.
The "!" operator is a "force unwrap" operator. It says "trust me. I know what I am doing. I guarantee that when this code runs, the variable will not contain nil." If you are wrong, you crash.
Unless you really do know what you are doing, avoid the "!" force unwrap operator. It is probably the largest source of crashes for beginning Swift programmers.
How to deal with optionals:
There are lots of other ways of dealing with optionals that are safer. Here are some (not an exhaustive list)
You can use "optional binding" or "if let" to say "if this optional contains a value, save that value into a new, non-optional variable. If the optional does not contain a value, skip the body of this if statement".
Here is an example of optional binding with our foo
optional:
if let newFoo = foo //If let is called optional binding. {
print("foo is not nil")
} else {
print("foo is nil")
}
Note that the variable you define when you use optional biding only exists (is only "in scope") in the body of the if statement.
Alternately, you could use a guard statement, which lets you exit your function if the variable is nil:
func aFunc(foo: Int?) {
guard let newFoo = input else { return }
//For the rest of the function newFoo is a non-optional var
}
Guard statements were added in Swift 2. Guard lets you preserve the "golden path" through your code, and avoid ever-increasing levels of nested ifs that sometimes result from using "if let" optional binding.
There is also a construct called the "nil coalescing operator". It takes the form "optional_var ?? replacement_val". It returns a non-optional variable with the same type as the data contained in the optional. If the optional contains nil, it returns the value of the expression after the "??" symbol.
So you could use code like this:
let newFoo = foo ?? "nil" // "??" is the nil coalescing operator
print("foo = (newFoo)")
You could also use try/catch or guard error handling, but generally one of the other techniques above is cleaner.
EDIT:
Another, slightly more subtle gotcha with optionals is "implicitly unwrapped optionals. When we declare foo, we could say:
var foo: String!
In that case foo is still an optional, but you don't have to unwrap it to reference it. That means any time you try to reference foo, you crash if it's nil.
So this code:
var foo: String!
let upperFoo = foo.capitalizedString
Will crash on reference to foo's capitalizedString property even though we're not force-unwrapping foo. the print looks fine, but it's not.
Thus you want to be really careful with implicitly unwrapped optionals. (and perhaps even avoid them completely until you have a solid understanding of optionals.)
Bottom line: When you are first learning Swift, pretend the "!" character is not part of the language. It's likely to get you into trouble.
edited Nov 11 '17 at 11:40
answered Feb 28 '16 at 14:37
Duncan C
91.9k13114195
91.9k13114195
7
You should consider making this a public wiki.
– vacawama
Feb 28 '16 at 14:42
3
Edit your answer, and below the edit box on the right is a community wiki checkbox. You will no longer get rep for the answer, but I know this isn't a blatant rep grab anyway.
– vacawama
Feb 28 '16 at 14:49
2
meta.stackexchange.com/q/11740/200104
– vacawama
Feb 28 '16 at 14:55
6
Given that this question is asked a million times on the site, if I were going to take the time to post a self-answered question as the canonical answer to the question, I'd hope that the answer is far more complete than this. There's nothing aboutguard
clauses. There's nothing about use ofif var
which is just as valid a construct asif let
. There's nothing aboutwhere
clauses which I feel is worth mention when we're talking aboutif let
binding (it removes a whole layer of nesting in many cases). There's nothing about optional chaining.
– nhgrif
Feb 28 '16 at 22:00
6
And when you mention implicitly unwrapped optionals, you don't even mention that you can use all of the aforementioned optional tricks to safely unwrap implicitly unwrapped optionals. We also don't cover unwrapping multiple options in the same clause.
– nhgrif
Feb 28 '16 at 22:01
|
show 4 more comments
7
You should consider making this a public wiki.
– vacawama
Feb 28 '16 at 14:42
3
Edit your answer, and below the edit box on the right is a community wiki checkbox. You will no longer get rep for the answer, but I know this isn't a blatant rep grab anyway.
– vacawama
Feb 28 '16 at 14:49
2
meta.stackexchange.com/q/11740/200104
– vacawama
Feb 28 '16 at 14:55
6
Given that this question is asked a million times on the site, if I were going to take the time to post a self-answered question as the canonical answer to the question, I'd hope that the answer is far more complete than this. There's nothing aboutguard
clauses. There's nothing about use ofif var
which is just as valid a construct asif let
. There's nothing aboutwhere
clauses which I feel is worth mention when we're talking aboutif let
binding (it removes a whole layer of nesting in many cases). There's nothing about optional chaining.
– nhgrif
Feb 28 '16 at 22:00
6
And when you mention implicitly unwrapped optionals, you don't even mention that you can use all of the aforementioned optional tricks to safely unwrap implicitly unwrapped optionals. We also don't cover unwrapping multiple options in the same clause.
– nhgrif
Feb 28 '16 at 22:01
7
7
You should consider making this a public wiki.
– vacawama
Feb 28 '16 at 14:42
You should consider making this a public wiki.
– vacawama
Feb 28 '16 at 14:42
3
3
Edit your answer, and below the edit box on the right is a community wiki checkbox. You will no longer get rep for the answer, but I know this isn't a blatant rep grab anyway.
– vacawama
Feb 28 '16 at 14:49
Edit your answer, and below the edit box on the right is a community wiki checkbox. You will no longer get rep for the answer, but I know this isn't a blatant rep grab anyway.
– vacawama
Feb 28 '16 at 14:49
2
2
meta.stackexchange.com/q/11740/200104
– vacawama
Feb 28 '16 at 14:55
meta.stackexchange.com/q/11740/200104
– vacawama
Feb 28 '16 at 14:55
6
6
Given that this question is asked a million times on the site, if I were going to take the time to post a self-answered question as the canonical answer to the question, I'd hope that the answer is far more complete than this. There's nothing about
guard
clauses. There's nothing about use of if var
which is just as valid a construct as if let
. There's nothing about where
clauses which I feel is worth mention when we're talking about if let
binding (it removes a whole layer of nesting in many cases). There's nothing about optional chaining.– nhgrif
Feb 28 '16 at 22:00
Given that this question is asked a million times on the site, if I were going to take the time to post a self-answered question as the canonical answer to the question, I'd hope that the answer is far more complete than this. There's nothing about
guard
clauses. There's nothing about use of if var
which is just as valid a construct as if let
. There's nothing about where
clauses which I feel is worth mention when we're talking about if let
binding (it removes a whole layer of nesting in many cases). There's nothing about optional chaining.– nhgrif
Feb 28 '16 at 22:00
6
6
And when you mention implicitly unwrapped optionals, you don't even mention that you can use all of the aforementioned optional tricks to safely unwrap implicitly unwrapped optionals. We also don't cover unwrapping multiple options in the same clause.
– nhgrif
Feb 28 '16 at 22:01
And when you mention implicitly unwrapped optionals, you don't even mention that you can use all of the aforementioned optional tricks to safely unwrap implicitly unwrapped optionals. We also don't cover unwrapping multiple options in the same clause.
– nhgrif
Feb 28 '16 at 22:01
|
show 4 more comments
First, you should know what an Optional value is.
You can step to The Swift Programming Launage
for detail.
Second, you should know the optional value has two status. One is the full value, and the other is nil value. So before you implement an optional value, you should check which state it's.
You can use if let ...
or guard let ... else
and so on.
One other way, if you don't want to check it's state before your implement, you can also use var buildingName = buildingName ?? "buildingName"
instead.
add a comment |
First, you should know what an Optional value is.
You can step to The Swift Programming Launage
for detail.
Second, you should know the optional value has two status. One is the full value, and the other is nil value. So before you implement an optional value, you should check which state it's.
You can use if let ...
or guard let ... else
and so on.
One other way, if you don't want to check it's state before your implement, you can also use var buildingName = buildingName ?? "buildingName"
instead.
add a comment |
First, you should know what an Optional value is.
You can step to The Swift Programming Launage
for detail.
Second, you should know the optional value has two status. One is the full value, and the other is nil value. So before you implement an optional value, you should check which state it's.
You can use if let ...
or guard let ... else
and so on.
One other way, if you don't want to check it's state before your implement, you can also use var buildingName = buildingName ?? "buildingName"
instead.
First, you should know what an Optional value is.
You can step to The Swift Programming Launage
for detail.
Second, you should know the optional value has two status. One is the full value, and the other is nil value. So before you implement an optional value, you should check which state it's.
You can use if let ...
or guard let ... else
and so on.
One other way, if you don't want to check it's state before your implement, you can also use var buildingName = buildingName ?? "buildingName"
instead.
answered Jul 30 '16 at 7:18
community wiki
QiunCheng
add a comment |
add a comment |
Since the above answers clearly explains how to play safely with Optionals.
I will try explain what Optionals are really in swift.
Another way to declare an optional variable is
var i : Optional<Int>
And Optional type is nothing but an enumeration with two cases, i.e
enum Optional<Wrapped> : ExpressibleByNilLiteral {
case none
case some(Wrapped)
.
.
.
}
So to assign a nil to our variable 'i'. We can do
var i = Optional<Int>.none
or to assign a value, we will pass some value
var i = Optional<Int>.some(28)
According to swift, 'nil' is the absence of value.
And to create an instance initialized with nil
We have to conform to a protocol called ExpressibleByNilLiteral
and great if you guessed it, only Optionals
conform to ExpressibleByNilLiteral
and conforming to other types is discouraged.
ExpressibleByNilLiteral
has a single method called init(nilLiteral:)
which initializes an instace with nil. You usually wont call this method and according to swift documentation it is discouraged to call this initializer directly as the compiler calls it whenever you initialize an Optional type with nil
literal.
Even myself has to wrap (no pun intended) my head around Optionals :D
Happy Swfting All.
add a comment |
Since the above answers clearly explains how to play safely with Optionals.
I will try explain what Optionals are really in swift.
Another way to declare an optional variable is
var i : Optional<Int>
And Optional type is nothing but an enumeration with two cases, i.e
enum Optional<Wrapped> : ExpressibleByNilLiteral {
case none
case some(Wrapped)
.
.
.
}
So to assign a nil to our variable 'i'. We can do
var i = Optional<Int>.none
or to assign a value, we will pass some value
var i = Optional<Int>.some(28)
According to swift, 'nil' is the absence of value.
And to create an instance initialized with nil
We have to conform to a protocol called ExpressibleByNilLiteral
and great if you guessed it, only Optionals
conform to ExpressibleByNilLiteral
and conforming to other types is discouraged.
ExpressibleByNilLiteral
has a single method called init(nilLiteral:)
which initializes an instace with nil. You usually wont call this method and according to swift documentation it is discouraged to call this initializer directly as the compiler calls it whenever you initialize an Optional type with nil
literal.
Even myself has to wrap (no pun intended) my head around Optionals :D
Happy Swfting All.
add a comment |
Since the above answers clearly explains how to play safely with Optionals.
I will try explain what Optionals are really in swift.
Another way to declare an optional variable is
var i : Optional<Int>
And Optional type is nothing but an enumeration with two cases, i.e
enum Optional<Wrapped> : ExpressibleByNilLiteral {
case none
case some(Wrapped)
.
.
.
}
So to assign a nil to our variable 'i'. We can do
var i = Optional<Int>.none
or to assign a value, we will pass some value
var i = Optional<Int>.some(28)
According to swift, 'nil' is the absence of value.
And to create an instance initialized with nil
We have to conform to a protocol called ExpressibleByNilLiteral
and great if you guessed it, only Optionals
conform to ExpressibleByNilLiteral
and conforming to other types is discouraged.
ExpressibleByNilLiteral
has a single method called init(nilLiteral:)
which initializes an instace with nil. You usually wont call this method and according to swift documentation it is discouraged to call this initializer directly as the compiler calls it whenever you initialize an Optional type with nil
literal.
Even myself has to wrap (no pun intended) my head around Optionals :D
Happy Swfting All.
Since the above answers clearly explains how to play safely with Optionals.
I will try explain what Optionals are really in swift.
Another way to declare an optional variable is
var i : Optional<Int>
And Optional type is nothing but an enumeration with two cases, i.e
enum Optional<Wrapped> : ExpressibleByNilLiteral {
case none
case some(Wrapped)
.
.
.
}
So to assign a nil to our variable 'i'. We can do
var i = Optional<Int>.none
or to assign a value, we will pass some value
var i = Optional<Int>.some(28)
According to swift, 'nil' is the absence of value.
And to create an instance initialized with nil
We have to conform to a protocol called ExpressibleByNilLiteral
and great if you guessed it, only Optionals
conform to ExpressibleByNilLiteral
and conforming to other types is discouraged.
ExpressibleByNilLiteral
has a single method called init(nilLiteral:)
which initializes an instace with nil. You usually wont call this method and according to swift documentation it is discouraged to call this initializer directly as the compiler calls it whenever you initialize an Optional type with nil
literal.
Even myself has to wrap (no pun intended) my head around Optionals :D
Happy Swfting All.
answered Nov 17 '17 at 16:15
community wiki
Tharzeez
add a comment |
add a comment |
I had this error once when I was trying to set my Outlets values from the prepare for segue method as follows:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? DestinationVC{
if let item = sender as? DataItem{
// This line pops up the error
destination.nameLabel.text = item.name
}
}
}
Then I found out that I can't set the values of the destination controller outlets because the controller hasn't been loaded or initialized yet.
So I solved it this way:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? DestinationVC{
if let item = sender as? DataItem{
// Created this method in the destination Controller to update its outlets after it's being initialized and loaded
destination.updateView(itemData: item)
}
}
}
Destination Controller:
// This variable to hold the data received to update the Label text after the VIEW DID LOAD
var name = ""
// Outlets
@IBOutlet weak var nameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
nameLabel.text = name
}
func updateView(itemDate: ObjectModel) {
name = itemDate.name
}
I hope this answer helps anyone out there with the same issue as I found the marked answer is great resource to the understanding of optionals and how they work but hasn't addressed the issue itself directly.
add a comment |
I had this error once when I was trying to set my Outlets values from the prepare for segue method as follows:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? DestinationVC{
if let item = sender as? DataItem{
// This line pops up the error
destination.nameLabel.text = item.name
}
}
}
Then I found out that I can't set the values of the destination controller outlets because the controller hasn't been loaded or initialized yet.
So I solved it this way:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? DestinationVC{
if let item = sender as? DataItem{
// Created this method in the destination Controller to update its outlets after it's being initialized and loaded
destination.updateView(itemData: item)
}
}
}
Destination Controller:
// This variable to hold the data received to update the Label text after the VIEW DID LOAD
var name = ""
// Outlets
@IBOutlet weak var nameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
nameLabel.text = name
}
func updateView(itemDate: ObjectModel) {
name = itemDate.name
}
I hope this answer helps anyone out there with the same issue as I found the marked answer is great resource to the understanding of optionals and how they work but hasn't addressed the issue itself directly.
add a comment |
I had this error once when I was trying to set my Outlets values from the prepare for segue method as follows:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? DestinationVC{
if let item = sender as? DataItem{
// This line pops up the error
destination.nameLabel.text = item.name
}
}
}
Then I found out that I can't set the values of the destination controller outlets because the controller hasn't been loaded or initialized yet.
So I solved it this way:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? DestinationVC{
if let item = sender as? DataItem{
// Created this method in the destination Controller to update its outlets after it's being initialized and loaded
destination.updateView(itemData: item)
}
}
}
Destination Controller:
// This variable to hold the data received to update the Label text after the VIEW DID LOAD
var name = ""
// Outlets
@IBOutlet weak var nameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
nameLabel.text = name
}
func updateView(itemDate: ObjectModel) {
name = itemDate.name
}
I hope this answer helps anyone out there with the same issue as I found the marked answer is great resource to the understanding of optionals and how they work but hasn't addressed the issue itself directly.
I had this error once when I was trying to set my Outlets values from the prepare for segue method as follows:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? DestinationVC{
if let item = sender as? DataItem{
// This line pops up the error
destination.nameLabel.text = item.name
}
}
}
Then I found out that I can't set the values of the destination controller outlets because the controller hasn't been loaded or initialized yet.
So I solved it this way:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? DestinationVC{
if let item = sender as? DataItem{
// Created this method in the destination Controller to update its outlets after it's being initialized and loaded
destination.updateView(itemData: item)
}
}
}
Destination Controller:
// This variable to hold the data received to update the Label text after the VIEW DID LOAD
var name = ""
// Outlets
@IBOutlet weak var nameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
nameLabel.text = name
}
func updateView(itemDate: ObjectModel) {
name = itemDate.name
}
I hope this answer helps anyone out there with the same issue as I found the marked answer is great resource to the understanding of optionals and how they work but hasn't addressed the issue itself directly.
answered Apr 13 at 14:06
community wiki
Wissa
add a comment |
add a comment |
Basically you tried to use a nil value in places where Swift allows only non-nil ones, by "fooling" the compiler to think there is nil value there, thus allowing your app to compile.
There are several scenarios that lead to this kind of fatal error:
forced unwraps:
let user = someVariable!
If
someVariable
is nil, then you'll get a crash. By doing a force unwrap you moved the nil check responsibility from the compiler to you, basically by doing a forced unwrap you're guaranteeing to the compiler that you'll never have nil values there. And guess what it happens if this happens?
Solution? Use optional binding (aka if-let), do the variable processing there:
if user = someVariable {
// do your stuff
}
forced casts:
let myRectangle = someShape as! Rectangle
Here by force casting you tell the compiler to no longer worry, as you'll always have a
Rectangle
instance there. And as long as that holds, you don't have to worry. The problems start when you or your colleagues from the project start circulating non-rectangle values.
Solution? Use optional binding (aka if-let), do the variable processing there:
if let myRectangle = someShape as? Rectangle {
// yay, I have a rectangle
}
Implicitly unwrapped optionals. Let's assume you have the following class definition:
class User {
var name: String!
init() {
name = "none yet"
}
func nicerName() {
return "Mr/Ms " + name
}
}
Now, if no-one messes up with the
name
property by setting it tonil
, then it works as expected, however ifUser
is initialized from a JSON that lacks thename
key, then you get the fatal error when trying to use the property.
Solution? Don't use them :) Unless you're 102% sure that the property will always have a non-nil value by the time it needs to be used. However in most cases converting it to an optional or non-optional will work. Making it non-optional will also result in the compiler helping you by telling the code paths you missed giving a value to that property
Unconnected outlets. This is a particular case of scenario #3. Basically you have some XIB-loaded class that you want to use.
class SignInViewController: UIViewController {
@IBOutlet var emailTextField: UITextField!
}
Now if you missed connecting the outlet from the XIB editor, then the app will crash as soon as you'll want to use the outlet.
Solution? Make sure all outlets are connected. Or use the?
operator on them:emailTextField?.text = "my@email.com"
. Or declare the outlet as optional, though in this case the compiler will force you to unwrap it all over the code.
Values coming from Objective-C, and that don't have nullability annotations. Let's assume we have the following Objective-C class:
@interface User: NSObject
@property NSString *name;
@end
Now if no nullability annotations are specified (either explicitly or via
NS_ASSUME_NONNULL_BEGIN
/NS_ASSUME_NONNULL_END
), then thename
property will be imported in Swift asString!
(an IUO - implicitly unwrapped optional). As soon as some swift code will want to use the value, it will crash, in nil cases.
Solution? Add nullability annotations to your Objective-C code. Beware though, the Objective-C compiler is a little bit permissive when it comes to nullability, you might end up with nil values, even if you explicitly marked them as
nonnull
.
add a comment |
Basically you tried to use a nil value in places where Swift allows only non-nil ones, by "fooling" the compiler to think there is nil value there, thus allowing your app to compile.
There are several scenarios that lead to this kind of fatal error:
forced unwraps:
let user = someVariable!
If
someVariable
is nil, then you'll get a crash. By doing a force unwrap you moved the nil check responsibility from the compiler to you, basically by doing a forced unwrap you're guaranteeing to the compiler that you'll never have nil values there. And guess what it happens if this happens?
Solution? Use optional binding (aka if-let), do the variable processing there:
if user = someVariable {
// do your stuff
}
forced casts:
let myRectangle = someShape as! Rectangle
Here by force casting you tell the compiler to no longer worry, as you'll always have a
Rectangle
instance there. And as long as that holds, you don't have to worry. The problems start when you or your colleagues from the project start circulating non-rectangle values.
Solution? Use optional binding (aka if-let), do the variable processing there:
if let myRectangle = someShape as? Rectangle {
// yay, I have a rectangle
}
Implicitly unwrapped optionals. Let's assume you have the following class definition:
class User {
var name: String!
init() {
name = "none yet"
}
func nicerName() {
return "Mr/Ms " + name
}
}
Now, if no-one messes up with the
name
property by setting it tonil
, then it works as expected, however ifUser
is initialized from a JSON that lacks thename
key, then you get the fatal error when trying to use the property.
Solution? Don't use them :) Unless you're 102% sure that the property will always have a non-nil value by the time it needs to be used. However in most cases converting it to an optional or non-optional will work. Making it non-optional will also result in the compiler helping you by telling the code paths you missed giving a value to that property
Unconnected outlets. This is a particular case of scenario #3. Basically you have some XIB-loaded class that you want to use.
class SignInViewController: UIViewController {
@IBOutlet var emailTextField: UITextField!
}
Now if you missed connecting the outlet from the XIB editor, then the app will crash as soon as you'll want to use the outlet.
Solution? Make sure all outlets are connected. Or use the?
operator on them:emailTextField?.text = "my@email.com"
. Or declare the outlet as optional, though in this case the compiler will force you to unwrap it all over the code.
Values coming from Objective-C, and that don't have nullability annotations. Let's assume we have the following Objective-C class:
@interface User: NSObject
@property NSString *name;
@end
Now if no nullability annotations are specified (either explicitly or via
NS_ASSUME_NONNULL_BEGIN
/NS_ASSUME_NONNULL_END
), then thename
property will be imported in Swift asString!
(an IUO - implicitly unwrapped optional). As soon as some swift code will want to use the value, it will crash, in nil cases.
Solution? Add nullability annotations to your Objective-C code. Beware though, the Objective-C compiler is a little bit permissive when it comes to nullability, you might end up with nil values, even if you explicitly marked them as
nonnull
.
add a comment |
Basically you tried to use a nil value in places where Swift allows only non-nil ones, by "fooling" the compiler to think there is nil value there, thus allowing your app to compile.
There are several scenarios that lead to this kind of fatal error:
forced unwraps:
let user = someVariable!
If
someVariable
is nil, then you'll get a crash. By doing a force unwrap you moved the nil check responsibility from the compiler to you, basically by doing a forced unwrap you're guaranteeing to the compiler that you'll never have nil values there. And guess what it happens if this happens?
Solution? Use optional binding (aka if-let), do the variable processing there:
if user = someVariable {
// do your stuff
}
forced casts:
let myRectangle = someShape as! Rectangle
Here by force casting you tell the compiler to no longer worry, as you'll always have a
Rectangle
instance there. And as long as that holds, you don't have to worry. The problems start when you or your colleagues from the project start circulating non-rectangle values.
Solution? Use optional binding (aka if-let), do the variable processing there:
if let myRectangle = someShape as? Rectangle {
// yay, I have a rectangle
}
Implicitly unwrapped optionals. Let's assume you have the following class definition:
class User {
var name: String!
init() {
name = "none yet"
}
func nicerName() {
return "Mr/Ms " + name
}
}
Now, if no-one messes up with the
name
property by setting it tonil
, then it works as expected, however ifUser
is initialized from a JSON that lacks thename
key, then you get the fatal error when trying to use the property.
Solution? Don't use them :) Unless you're 102% sure that the property will always have a non-nil value by the time it needs to be used. However in most cases converting it to an optional or non-optional will work. Making it non-optional will also result in the compiler helping you by telling the code paths you missed giving a value to that property
Unconnected outlets. This is a particular case of scenario #3. Basically you have some XIB-loaded class that you want to use.
class SignInViewController: UIViewController {
@IBOutlet var emailTextField: UITextField!
}
Now if you missed connecting the outlet from the XIB editor, then the app will crash as soon as you'll want to use the outlet.
Solution? Make sure all outlets are connected. Or use the?
operator on them:emailTextField?.text = "my@email.com"
. Or declare the outlet as optional, though in this case the compiler will force you to unwrap it all over the code.
Values coming from Objective-C, and that don't have nullability annotations. Let's assume we have the following Objective-C class:
@interface User: NSObject
@property NSString *name;
@end
Now if no nullability annotations are specified (either explicitly or via
NS_ASSUME_NONNULL_BEGIN
/NS_ASSUME_NONNULL_END
), then thename
property will be imported in Swift asString!
(an IUO - implicitly unwrapped optional). As soon as some swift code will want to use the value, it will crash, in nil cases.
Solution? Add nullability annotations to your Objective-C code. Beware though, the Objective-C compiler is a little bit permissive when it comes to nullability, you might end up with nil values, even if you explicitly marked them as
nonnull
.
Basically you tried to use a nil value in places where Swift allows only non-nil ones, by "fooling" the compiler to think there is nil value there, thus allowing your app to compile.
There are several scenarios that lead to this kind of fatal error:
forced unwraps:
let user = someVariable!
If
someVariable
is nil, then you'll get a crash. By doing a force unwrap you moved the nil check responsibility from the compiler to you, basically by doing a forced unwrap you're guaranteeing to the compiler that you'll never have nil values there. And guess what it happens if this happens?
Solution? Use optional binding (aka if-let), do the variable processing there:
if user = someVariable {
// do your stuff
}
forced casts:
let myRectangle = someShape as! Rectangle
Here by force casting you tell the compiler to no longer worry, as you'll always have a
Rectangle
instance there. And as long as that holds, you don't have to worry. The problems start when you or your colleagues from the project start circulating non-rectangle values.
Solution? Use optional binding (aka if-let), do the variable processing there:
if let myRectangle = someShape as? Rectangle {
// yay, I have a rectangle
}
Implicitly unwrapped optionals. Let's assume you have the following class definition:
class User {
var name: String!
init() {
name = "none yet"
}
func nicerName() {
return "Mr/Ms " + name
}
}
Now, if no-one messes up with the
name
property by setting it tonil
, then it works as expected, however ifUser
is initialized from a JSON that lacks thename
key, then you get the fatal error when trying to use the property.
Solution? Don't use them :) Unless you're 102% sure that the property will always have a non-nil value by the time it needs to be used. However in most cases converting it to an optional or non-optional will work. Making it non-optional will also result in the compiler helping you by telling the code paths you missed giving a value to that property
Unconnected outlets. This is a particular case of scenario #3. Basically you have some XIB-loaded class that you want to use.
class SignInViewController: UIViewController {
@IBOutlet var emailTextField: UITextField!
}
Now if you missed connecting the outlet from the XIB editor, then the app will crash as soon as you'll want to use the outlet.
Solution? Make sure all outlets are connected. Or use the?
operator on them:emailTextField?.text = "my@email.com"
. Or declare the outlet as optional, though in this case the compiler will force you to unwrap it all over the code.
Values coming from Objective-C, and that don't have nullability annotations. Let's assume we have the following Objective-C class:
@interface User: NSObject
@property NSString *name;
@end
Now if no nullability annotations are specified (either explicitly or via
NS_ASSUME_NONNULL_BEGIN
/NS_ASSUME_NONNULL_END
), then thename
property will be imported in Swift asString!
(an IUO - implicitly unwrapped optional). As soon as some swift code will want to use the value, it will crash, in nil cases.
Solution? Add nullability annotations to your Objective-C code. Beware though, the Objective-C compiler is a little bit permissive when it comes to nullability, you might end up with nil values, even if you explicitly marked them as
nonnull
.
edited Oct 12 at 22:38
community wiki
3 revs
Cristik
add a comment |
add a comment |
This is more of a important comment and that why implicitly unwrapped optionals can be deceptive when it comes to debugging nil
values.
Think of the following code:
It compiles with no errors/warnings:
c1.address.city = c3.address.city
Yet at runtime it gives the following error: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Can you tell me which object is nil
?
You can't!
The full code would be:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var c1 = NormalContact()
let c3 = BadContact()
c1.address.city = c3.address.city // compiler hides the truth from you and then you sudden get a crash
}
}
struct NormalContact {
var address : Address = Address(city: "defaultCity")
}
struct BadContact {
var address : Address!
}
struct Address {
var city : String
}
Long story short by using var address : Address!
you're hiding the possibility that a variable can be nil
from other readers. And when it crashes you're like "what the hell?! my address
isn't an optional, so why am I crashing?!.
Hence it's better to write as such:
c1.address.city = c2.address!.city // ERROR: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Can you now tell me which object it is that was nil
?
This time the code has been made more clear to you. You can rationalize and think that likely it's the address
parameter that was forcefully unwrapped.
The full code would be :
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var c1 = NormalContact()
let c2 = GoodContact()
c1.address.city = c2.address!.city
c1.address.city = c2.address?.city // not compile-able. No deceiving by the compiler
c1.address.city = c2.address.city // not compile-able. No deceiving by the compiler
if let city = c2.address?.city { // safest approach. But that's not what I'm talking about here.
c1.address.city = city
}
}
}
struct NormalContact {
var address : Address = Address(city: "defaultCity")
}
struct GoodContact {
var address : Address?
}
struct Address {
var city : String
}
add a comment |
This is more of a important comment and that why implicitly unwrapped optionals can be deceptive when it comes to debugging nil
values.
Think of the following code:
It compiles with no errors/warnings:
c1.address.city = c3.address.city
Yet at runtime it gives the following error: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Can you tell me which object is nil
?
You can't!
The full code would be:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var c1 = NormalContact()
let c3 = BadContact()
c1.address.city = c3.address.city // compiler hides the truth from you and then you sudden get a crash
}
}
struct NormalContact {
var address : Address = Address(city: "defaultCity")
}
struct BadContact {
var address : Address!
}
struct Address {
var city : String
}
Long story short by using var address : Address!
you're hiding the possibility that a variable can be nil
from other readers. And when it crashes you're like "what the hell?! my address
isn't an optional, so why am I crashing?!.
Hence it's better to write as such:
c1.address.city = c2.address!.city // ERROR: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Can you now tell me which object it is that was nil
?
This time the code has been made more clear to you. You can rationalize and think that likely it's the address
parameter that was forcefully unwrapped.
The full code would be :
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var c1 = NormalContact()
let c2 = GoodContact()
c1.address.city = c2.address!.city
c1.address.city = c2.address?.city // not compile-able. No deceiving by the compiler
c1.address.city = c2.address.city // not compile-able. No deceiving by the compiler
if let city = c2.address?.city { // safest approach. But that's not what I'm talking about here.
c1.address.city = city
}
}
}
struct NormalContact {
var address : Address = Address(city: "defaultCity")
}
struct GoodContact {
var address : Address?
}
struct Address {
var city : String
}
add a comment |
This is more of a important comment and that why implicitly unwrapped optionals can be deceptive when it comes to debugging nil
values.
Think of the following code:
It compiles with no errors/warnings:
c1.address.city = c3.address.city
Yet at runtime it gives the following error: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Can you tell me which object is nil
?
You can't!
The full code would be:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var c1 = NormalContact()
let c3 = BadContact()
c1.address.city = c3.address.city // compiler hides the truth from you and then you sudden get a crash
}
}
struct NormalContact {
var address : Address = Address(city: "defaultCity")
}
struct BadContact {
var address : Address!
}
struct Address {
var city : String
}
Long story short by using var address : Address!
you're hiding the possibility that a variable can be nil
from other readers. And when it crashes you're like "what the hell?! my address
isn't an optional, so why am I crashing?!.
Hence it's better to write as such:
c1.address.city = c2.address!.city // ERROR: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Can you now tell me which object it is that was nil
?
This time the code has been made more clear to you. You can rationalize and think that likely it's the address
parameter that was forcefully unwrapped.
The full code would be :
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var c1 = NormalContact()
let c2 = GoodContact()
c1.address.city = c2.address!.city
c1.address.city = c2.address?.city // not compile-able. No deceiving by the compiler
c1.address.city = c2.address.city // not compile-able. No deceiving by the compiler
if let city = c2.address?.city { // safest approach. But that's not what I'm talking about here.
c1.address.city = city
}
}
}
struct NormalContact {
var address : Address = Address(city: "defaultCity")
}
struct GoodContact {
var address : Address?
}
struct Address {
var city : String
}
This is more of a important comment and that why implicitly unwrapped optionals can be deceptive when it comes to debugging nil
values.
Think of the following code:
It compiles with no errors/warnings:
c1.address.city = c3.address.city
Yet at runtime it gives the following error: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Can you tell me which object is nil
?
You can't!
The full code would be:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var c1 = NormalContact()
let c3 = BadContact()
c1.address.city = c3.address.city // compiler hides the truth from you and then you sudden get a crash
}
}
struct NormalContact {
var address : Address = Address(city: "defaultCity")
}
struct BadContact {
var address : Address!
}
struct Address {
var city : String
}
Long story short by using var address : Address!
you're hiding the possibility that a variable can be nil
from other readers. And when it crashes you're like "what the hell?! my address
isn't an optional, so why am I crashing?!.
Hence it's better to write as such:
c1.address.city = c2.address!.city // ERROR: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Can you now tell me which object it is that was nil
?
This time the code has been made more clear to you. You can rationalize and think that likely it's the address
parameter that was forcefully unwrapped.
The full code would be :
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var c1 = NormalContact()
let c2 = GoodContact()
c1.address.city = c2.address!.city
c1.address.city = c2.address?.city // not compile-able. No deceiving by the compiler
c1.address.city = c2.address.city // not compile-able. No deceiving by the compiler
if let city = c2.address?.city { // safest approach. But that's not what I'm talking about here.
c1.address.city = city
}
}
}
struct NormalContact {
var address : Address = Address(city: "defaultCity")
}
struct GoodContact {
var address : Address?
}
struct Address {
var city : String
}
edited Nov 1 at 4:50
community wiki
2 revs
Honey
add a comment |
add a comment |
protected by jtbandes Jul 30 '16 at 19:56
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
5
@RobertColumbia, this is a Community Wiki Q&A pair with extensive documentation of the issue, I don't think this question should be closed for a lack of a MCVE.
– JAL
Sep 25 '17 at 0:44