How to Use them (With Examples) (2024)

In the previous article, we learned about different data types available in Swift and also noticed variable or constant declared of those types contains a default value.

Example:

let someValue = Int()print(someValue)

When you run the program, the output will be:

0

However there is another data type in Swift called Optional, whose default value is a null value (nil). You can use optional when you want a variable or constant contain no value in it. An optional type may contain a value or absent a value (a null value).

Non technically, you can think optional as a shoe box. The shoe box may or may not contain a shoe in it. So, you should know beforehand while accessing the shoe from the box.

How to declare an Optional?

You can simply represent a Data type as Optional by appending ! or ? to the Type. If an optional contains a value in it, it returns value as Optional<Value>, if not it returns nil.

Example 1: How to declare an optional in Swift?

var someValue:Int?var someAnotherValue:Int!print(someValue)print(someAnotherValue)

When you run the program, the output will be:

nilnil

In the above program, we have initialized a optional type using ? and !. Both ways are valid to create an optional but there is one major difference which we will explore below.

Declaring an optional Int means the variable will either have an integer value or no value. Since no value is assigned to the variable, you can see both print statement outputs nil on the screen.

Example 2: Assigning and accessing a value from an optional

let someValue:Int? = 5print(someValue)print(someValue!)

When you run the program, the output will be:

Optional(5)5

In the above program, we have declared an optional of Int type and assigned value 5 in it.

As you can see, printing the optional as print(someValue) doesn't give you 5 but Optional(5). It is of the form as described above: Optional<Value>. In order to access the <Value> from it, we need a mechanism called unwrapping.

You can unwrap an optional by appending ! character at the end of the variable/constant as in the next line print(someValue!). print(someValue!) unwraps the optional and outputs 5 on the screen.

However, remember, this kind of unwrapping mechanism should only be used when you are certain that the optional will sure have a value when you access it.

Example 3: Explicitly declaring an unwrapped optional

You can also create an unwrapped optional as:

let someValue:Int! = 5print(someValue)

When you run the program, the output will be:

5

In the above program, Int! creates a unwrapped optional, which automatically unwraps the value while you access it so that you don't need to everytime append the ! character.

Be certain while you use these kinds of optionals, the variable will always need to have a value when you access it. If you don't, you will get a fatal error crash.

Example 4: Fatal error when accessing a null unwrapped optional

var someValue:Int!var unwrappedValue:Int = someValue //crashes due to this line

When you run the program, you will get a crash as fatal error: unexpectedly found nil while unwrapping an Optional value because the code unwrappedValue:Int = someValue tries to assign value from Optional someValue to variable unwrappedValue.

However, somevalue is an Optional type that contains nil value. Trying to assign nil value to variable unwrappedValue which is not an optional will lead to crash.

There are different techniques to handle this case which are explained below.

Optional Handling

In order to use value of an optional, it needs to be unwrapped. Better way to use optional value is by conditional unwrapping rather than force unwrapping using ! operator.

This is because conditionally unwrapping asks Check if this variable has a value? . If yes, give the value, otherwise it will handle the nil case.

On the contrary, force unwrapping says This variable does have a value while you use it. Therefore, when you force unwrap a variable that is nil, your program will throw an unexpectedly found nil while unwrapping an optional exception and crash. Some of the techniques for conditional unwrapping are explained below:

1. If-statement

You can use if statement and compare optional with nil to find out whether a optional contains a value or not. You can use the comparison operator "equal to" operator (==) or the "not equal to" operator (!=) in the if statement.

Example 5: Optional handling with if else statement

var someValue:Int?var someAnotherValue:Int! = 0 if someValue != nil {print("It has some value \(someValue!)")} else {print("doesn't contain value")} if someAnotherValue != nil {print("It has some value \(someAnotherValue!)")} else {print("doesn't contain value")}

When you run the program, the output will be:

doesn't contain valueIt has some value 0

In the above program, the code inside if statement executes if an optional contain a value, otherwise the statement inside the else block executes. The major drawback of optional handling using this technique is, you still need to unwrap the value from optional using ! operator.

2. Optional Binding (if-let)

Optional binding helps you to find out whether an optional contains a value or not. If an optional contains a value, that value is available as a temporary constant or variable. Therefore, optional binding can be used with if statement to check for a value inside an optional, and to extract that value into a constant or variable in a single action.

Example 5: Optional handling using if let statement

var someValue:Int?var someAnotherValue:Int! = 0 if let temp = someValue {print("It has some value \(temp)") } else {print("doesn't contain value")} if let temp = someAnotherValue {print("It has some value \(temp)")} else {print("doesn't contain value") }

When you run the program, the output will be:

doesn't contain valueIt has some value 0

In the above program, the code inside if statement executes if the optional contains a value. Otherwise the else block gets executed. The if-let statement also automatically unwraps the value and places the unwrapped value in temp constant. This technique has major advantage because you don't need to forcely unwrap the value although being certain an optional contains a value.

3. Guard statement

You can use guard to handle optionals in Swift. Don't worry if you don't know what guard is. For now, just think of guard as an if-else condition with no if block. If the condition fails, else statement is executed. If not, next statement is executed. See Swift guard for more details.

Example 6: Optional handling using guard-let

func testFunction() {let someValue:Int? = 5guard let temp = someValue else {return}print("It has some value \(temp)")}testFunction()

When you run the program, the output will be:

It has some value 5

In the above program, the guard contains a condition whether an optional someValue contains a value or not. If it contains a value then guard-let statement automatically unwraps the value and places the unwrapped value in temp constant. Otherwise, else block gets executed and and it would return to the calling function. Since, the optional contains a value, print function is called.

4. Nil-coalescing operator

In Swift, you can also use nil-coalescing operator to check whether a optional contains a value or not. It is defined as (a ?? b). It unwraps an optional a and returns it if it contains a value, or returns a default value b if a is nil.

Example 7: Optional handling using nil-coalescing operator

var someValue:Int!let defaultValue = 5let unwrappedValue:Int = someValue ?? defaultValueprint(unwrappedValue)

When you run the program, the output will be:

5

In the above program, variable someValue is defined optional and contains nil value. The nil coalescing operator fails to unwrap the optional therefore returns defaultValue. Therefore the statement print(unwrappedValue) outputs 5 in the console.

var someValue:Int? = 10let defaultValue = 5let unwrappedValue:Int = someValue ?? defaultValueprint(unwrappedValue)

When you run the program, the output will be:

10

However, in the above program, optional variable someValue is initialized with value 10. So, the nil coalescing operator successfully unwraps the value from someValue. Therefore, the statement someValue ?? defaultValue returns 10 and the statement print(unwrappedValue) outputs 10 in the console.

How to Use them (With Examples) (2024)

FAQs

What are the rules for using enough? ›

When enough is after the adjective (big enough envelopes), it describes the adjective – the envelopes are too small. When enough is before the adjective (enough big envelopes), it describes the noun phrase – we have some big envelopes, but we need more.

How do you use them in grammar? ›

language note: Them is a third person pronoun. Them is used as the object of a verb or preposition. You use them to refer to a group of people, animals, or things.

How do you use enough to sample a sentence? ›

How to Use enough in a Sentence
  1. Have you got enough money?
  2. That's enough talk for now; let's get started.
  3. There's enough food for everyone.
  4. No, the two of us don't have enough time to write a book. ...
  5. There was the love that didn't last and the affection that wasn't enough.
Sep 5, 2024

What are sentences with enough is enough? ›

I have to say firmly that enough is enough. After seven years of membership, enough is enough. What emergency measures does he have to prevent the prison officers and the prisoners deciding to say, as they will soon, enough is enough? They are all saying the same thing: enough is enough.

Is enough singular or plural? ›

Enough can qualify count nouns in the plural, or non count nouns (which are by definition in the singular). Enough cannot normally be used to qualify a count noun in the singular.

How do you use enough said in a sentence? ›

"Someone has to explain the situation to her." "Enough said." "There are some, er, objections to her appointment." "Oh yes, enough said." She thinks the moon is made of cheese - enough said. "Put it this way: she can afford her own private jet." "Enough said."

How do you use them examples? ›

Them is used to refer to the object of a clause. In other words, it usually represents the group of people or things that have 'experienced' the action described by the verb, and refers back to two or more people or things that were mentioned earlier: I've bought some apples. I'll put them on the table.

How to make a sentence with them? ›

Examples from the Collins Corpus
  1. We must clear them out of the party & let them disappear. ...
  2. Be prepared to let them enter a room first. ...
  3. They avoided jail but know that another conviction could land them behind bars. ...
  4. Then they suddenly found a third party to assist them instead.

What is the use for them? ›

We often use them to refer back to people and things that we have already identified (underlined): … Personal subject pronouns act as the subject of a clause. We use them before a verb to show who is doing the verb. We do not usually leave out the pronoun: …

What is an example of enough? ›

Examples of enough in a Sentence

Adverb I couldn't run fast enough to catch up with her. She's old enough to know better. Are you rich enough to retire? That's good enough for me.

What is an example sentence for sure enough? ›

Examples from Collins dictionaries

Sure enough, it was delicious. I thought she'd recognised me, and sure enough, she came across. That's a sure-enough fact. He's a sure-enough man.

How do you use good enough in a sentence? ›

Good enough they didn't kill. He asked for my CV to look at briefly and good enough I had it on my phone.

What type of grammar is enough? ›

Enough is a determiner, a pronoun or an adverb. We use enough to mean 'as much as we need or want'.

What is an example of enough with nouns? ›

Examples
  • There is enough bread for lunch.
  • She has enough money.
  • There are not enough apples for all of us.
  • I don't have enough sugar to make a cake.

When should I say enough is enough? ›

If your partner refuses to let you out of your sight, violates your personal space, or tries to make decisions for you without your permission (telling you who you should/shouldn't be friends with, what you should wear, etc), it may be best to say enough is enough.

What is the good enough rule? ›

The Good Enough Principle refers to the idea that progress is a better goal than perfection in our role as co-survivors and caregivers. In reality, no one is perfect.

What is the rule of too and enough? ›

Too comes before the adjective or adverb it's describing, while enough comes after the adjective or adverb. Enough comes before a noun, whereas too is never used before a noun.

How do you use enough at the end of a sentence? ›

Yes. Examples: “I can't thank you enough.”

What is a negative sentence for enough? ›

Enough is used in negative sentences to mean less than sufficient or less than necessary. You're not working fast enough, you won't finish on time.

Top Articles
Winter Hunting – Drones for Effective Deer Recovery Efforts
Amazon Prime Day 2023 Day 2: The best deals you can still get
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Selly Medaline
Latest Posts
Article information

Author: Cheryll Lueilwitz

Last Updated:

Views: 6227

Rating: 4.3 / 5 (74 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Cheryll Lueilwitz

Birthday: 1997-12-23

Address: 4653 O'Kon Hill, Lake Juanstad, AR 65469

Phone: +494124489301

Job: Marketing Representative

Hobby: Reading, Ice skating, Foraging, BASE jumping, Hiking, Skateboarding, Kayaking

Introduction: My name is Cheryll Lueilwitz, I am a sparkling, clean, super, lucky, joyous, outstanding, lucky person who loves writing and wants to share my knowledge and understanding with you.