What Is an "Unwrapped Value" in Swift

What is an unwrapped value in Swift?

First, you have to understand what an Optional type is. An optional type basically means that the variable can be nil.

Example:

var canBeNil : Int? = 4
canBeNil = nil

The question mark indicates the fact that canBeNil can be nil.

This would not work:

var cantBeNil : Int = 4
cantBeNil = nil // can't do this

To get the value from your variable if it is optional, you have to unwrap it. This just means putting an exclamation point at the end.

var canBeNil : Int? = 4
println(canBeNil!)

Your code should look like this:

let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square") 
let sideLength = optionalSquare!.sideLength

A sidenote:

You can also declare optionals to automatically unwrap by using an exclamation mark instead of a question mark.

Example:

var canBeNil : Int! = 4
print(canBeNil) // no unwrapping needed

So an alternative way to fix your code is:

let optionalSquare: Square! = Square(sideLength: 2.5, name: "optional square") 
let sideLength = optionalSquare.sideLength

EDIT:

The difference that you're seeing is exactly the symptom of the fact that the optional value is wrapped. There is another layer on top of it. The unwrapped version just shows the straight object because it is, well, unwrapped.

A quick playground comparison:

playground

In the first and second cases, the object is not being automatically unwrapped, so you see two "layers" ({{...}}), whereas in the third case, you see only one layer ({...}) because the object is being automatically unwrapped.

The difference between the first case and the second two cases is that the second two cases will give you a runtime error if optionalSquare is set to nil. Using the syntax in the first case, you can do something like this:

if let sideLength = optionalSquare?.sideLength {
println("sideLength is not nil")
} else {
println("sidelength is nil")
}

What is to unwrap a variable?

1.Wrapped mean that you put the value in a variable, which maybe empty. For example:

let message: String? // message can be nil
message = "Hello World!" // the value "Hello World!" is wrapped inside the message variable.

print(message) // print the value that is wrapped in message - it can be null.

2.Unwrap means you get the value of the variable to use it.

textField?.text = "Hello World!" // you get the value of text field and set text to "Hello World!" if textField is not nil.
textField!.text = "Hello World!" // force unwrap the value of text field and set text to "Hello World!" if text field is not nil, other wise, the application will crash. (you want to make sure that textField muse exists).

3.Optional: is a variable that can be nil. When you use its value you need to unwrap it explicitly:

let textField: UITextField? // this is optional
textField?.text = "Hello World" // explicitly tells the compiler to unwrap it by putting an "?" here
textField!.text = "Hello World" // explicitly tells the compiler to unwrap it by putting in "!" here.

Implicitly unwrap optional(?) is an optional (value can be nil). But when you use it you don't have to tells the compiler to unwrap it. It will be forced unwrapped implicitly (default)

let textField: UITextField!
textField.text = "Hello World!" // it will forced unwrap the variable and the program will crash if the textField is nil.

4.Try to always use optional(?) in most case if you think the value can be nil. Use implicitly unwrapped optional(!) only when you are 100% sure that the variable can't be nil at the time you use it (but you can't set it in Class constructor).

5.Implicitly means automatically, you don't have to tell the compiler, it will do it automatically, and it's bad because sometime you don't know that you are unwrapping an optional that may cause the program crash. In programming, explicit always better that implicit.

Unwrapping an Optional value in swift and realm

As from comments if appears that your view is not yet loaded and some of your views are still nil. Your app crashes because in line limitLabel.text = limit[0].limitSum the limitLabel is nil. It would crash regardless of Realm even by calling limitLabel.text = "Hello world!"

You can always guard data that you need to avoid changes in your code. Simply add

guard let limitLabel = limitLabel else { return nil } 
guard let ForThePeriod = ForThePeriod else { return nil }

and so on.

I tried to clean up your code a bit. It is hard to understand what exactly are you trying to achieve but something like the following may seem a bit more appropriate:

func leftLabels() {
// Elements needed for method to execute.
guard let limitLabel = limitLabel else { return }
guard let forThePeriodLabel = forThePeriodLabel else { return }
guard let availableForSpendingLabel = availableForSpendingLabel else { return }

// Items that will be reused throughout the method later on
let limits: [Limit]
let firstLimit: Limit
let dates: (start: Date?, end: Date?)
let filterLimit: Int

limits = self.realm.objects(Limit.self)
guard limits.isEmpty == false else { return }
firstLimit = limits[0]

// limitLabel
limitLabel.text = firstLimit.limitSum

// Date components
dates = {
let calendar = Calendar.current
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"

let firstDay = firstLimit.limitDate as Date
let lastDay = firstLimit.limitLastDate as Date

let firstComponent = calendar.dateComponents([.year, .month, .day], from: firstDay)
let lastComponent = calendar.dateComponents([.year, .month, .day], from: lastDay)

let startDate = formatter.date(from: "\(firstComponent.year!)/\(firstComponent.month!)/\(firstComponent.day!) 00:00")
let endDate = formatter.date(from: "\(lastComponent.year!)/\(lastComponent.month!)/\(lastComponent.day!) 23:59")

return (startDate, endDate)
}()

// forThePeriodLabel
filterLimit = realm.objects(SpendingDB.self).filter("self.date >= %@ && self.date <= %@", startDate ?? "", endDate ?? "").sum(ofProperty: "cost")
forThePeriodLabel.text = String(filterLimit)

// availableForSpendingLabel
availableForSpendingLabel.text = {
guard let a = Int(firstLimit.limitSum) else { return "" }
let b = filterLimit
let c = a - b
return String(c)
}()
}

Note some practices which help you better to structure and solve your code.

  • Guard dangerous data at first
  • Create a list of reusable items for your method (there should be as fewer as possible, in most cases none). Note how these can be later assigned to. And if you try using it before assigning to it, you will be warned by your compiler.
  • Wrap as much code into closed sections such as availableForSpendingLabel.text = { ... code here ... }()
  • Use tuples such as let dates: (start: Date?, end: Date?)
  • Don't be afraid of using long names such as availableForSpendingLabel

I would even further try and break this down into multiple methods. But I am not sure what this method does and assume that you have posted only part of it...

========== EDIT: Adding alternate approach ==========

From comments this is a financial application so probably at least dealing with Decimal numbers would make sense. Also introducing approach with adding a new structure which resolves data internally. A formatter is also used to format the number. And some other improvements:

struct Limit {
let amount: Decimal
let startDate: Date
let endDate: Date
}

struct Spending {
let cost: Decimal
let date: Date
}

struct LimitReport {
let limitAmount: Decimal
let spendingSum: Decimal
let balance: Decimal

init(limit: Limit) {
let limitAmount: Decimal = limit.amount
let spendingSum: Decimal = {
let calendar = Calendar.autoupdatingCurrent // Is this OK or should it be some UTC or something?
func beginningOfDate(_ date: Date) -> Date {
let components = calendar.dateComponents([.day, .month, .year], from: date)
return calendar.date(from: components)!
}
let startDate = beginningOfDate(limit.startDate)
let endDate = calendar.date(byAdding: .day, value: 1, to: startDate)

let spendings: [Spending] = realm.objects(Spending.self).filter { $0.date >= startDate && $0.date < endDate }
return spendings.reduce(0, { $0 + $1.cost })
}()
let balance = limitAmount - spendingSum

self.limitAmount = limitAmount
self.spendingSum = spendingSum
self.balance = balance
}

}

func leftLabels() {
// Elements needed for method to execute.
guard let limitLabel = limitLabel else { return }
guard let forThePeriodLabel = forThePeriodLabel else { return }
guard let availableForSpendingLabel = availableForSpendingLabel else { return }

guard let limit = self.realm.objects(Limit.self).first else { return }

let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencySymbol = "$"

let report = LimitReport(limit: limit)

limitLabel.text = formatter.string(from: report.limitAmount)
forThePeriodLabel.text = formatter.string(from: report.spendingSum)
availableForSpendingLabel.text = formatter.string(from: report.balance)
}

Why does a `nil` implicitly unwrapped optional print `nil` and not crash?

That does not crash because print accepts Any as the first parameter. Are implicitly unwrapped optionals a kind of Any? Yes they are! Anything is Any. There is no need to unwrap the optional. An implicitly unwrapped optional can be used in a place where Any is expected without unwrapping the optional.

That could potentially be confusing because now you have something with type Any, which doesn't look like it's optional, but it is an optional under the hood. To avoid this, Swift will output a warning telling you that you are implicitly coercing whatever optional type to Any.

You need to use ! to force unwrap it here:

print(x!)

unwrapping an Optional value

First of all, it is a bad practice to use force unwrap (!) everywhere. Try to avoid it, until you really need it and/or know what are you doing. Here you use SwiftyJSON. It helps you to extract data from JSON in a convenient way. But you shouldn't rely, that you will always get proper JSON from the backend. There are many reasons why it can return wrong JSON and there would not be needed value. There are two options:

  1. You can use .stringValue instead of .string - it will return an empty string instead of nil
  2. You can do in this way: if let token = jsonData["access_token"].string {...} or even use guard statement

Here is a good article to understand force unwrapping: https://blog.timac.org/2017/0628-swift-banning-force-unwrapping-optionals/

What does Fatal error: Unexpectedly found nil while unwrapping an Optional value mean?

Background: What’s an Optional?

In Swift, Optional is an option type: it can contain any value from the original ("Wrapped") type, or no value at all (the special value nil). An optional value must be unwrapped before it can be used.

Optional is a generic type, which means that Optional and Optional are distinct types — the type inside <> is called the Wrapped type. Under the hood, an Optional is an enum with two cases: .some(Wrapped) and .none, where .none is equivalent to nil.

Optionals can be declared using the named type Optional, or (most commonly) as a shorthand with a ? suffix.

var anInt: Int = 42
var anOptionalInt: Int? = 42
var anotherOptionalInt: Int? // `nil` is the default when no value is provided
var aVerboseOptionalInt: Optional // equivalent to `Int?`

anOptionalInt = nil // now this variable contains nil instead of an integer

Optionals are a simple yet powerful tool to express your assumptions while writing code. The compiler can use this information to prevent you from making mistakes. From The Swift Programming Language:

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 requires a String, type safety prevents you from passing it an Int by mistake. Likewise, type safety prevents you from accidentally passing an optional String to a piece of code that requires a non-optional String. Type safety helps you catch and fix errors as early as possible in the development process.

Some other programming languages also have generic option types: for example, Maybe in Haskell, option in Rust, and optional in C++17.

In programming languages without option types, a particular "sentinel" value is often used to indicate the absence of a valid value. In Objective-C, for example, nil (the null pointer) represents the lack of an object. For primitive types such as int, a null pointer can't be used, so you would need either a separate variable (such as value: Int and isValid: Bool) or a designated sentinel value (such as -1 or INT_MIN). These approaches are error-prone because it's easy to forget to check isValid or to check for the sentinel value. Also, if a particular value is chosen as the sentinel, that means it can no longer be treated as a valid value.

Option types such as Swift's Optional solve these problems by introducing a special, separate nil value (so you don't have to designate a sentinel value), and by leveraging the strong type system so the compiler can help you remember to check for nil when necessary.



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.

crashed 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

Fatal error: Unexpectedly found nil while unwrapping an Optional value

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

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

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 fixing connections, try deleting the lines of code that define your outlets, then reconnect them.



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

Getting a value of Optional() even when unwrapping

When you access a dictionary it returns optional of it's value type because it doesn't know runtime whether certain key is available in the dictionary or not. If the key is present then it's value is returned but if it's not then we get nil value.

Use optional binding to access unwrapped value:

if let url = params["facebook_url"] {
print(url) // facebook url
}

In case double optional unwrapping:

if let urlOptional = params["facebook_url"], let value = urlOptional {
print(value) // facebook url
}

Note: Also check the source where you have set the value of 'facebook_url' key.



Related Topics



Leave a reply



Submit