DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Frameworks
  4. Dictionaries in Swift

Dictionaries in Swift

In this post, we introduce and delve into what exactly a dictionary is in Swift and how developers can use it.

Swathi Prasad user avatar by
Swathi Prasad
·
May. 08, 19 · Tutorial
Like (1)
Save
Tweet
Share
6.48K Views

Join the DZone community and get the full member experience.

Join For Free
Swift

Recently, I have been learning and coding in Swift. Swift is a powerful and general-purpose language. As a seasoned Java developer, I can correlate some of the Swift's concepts and it is easy to learn.

In this article, I would like to introduce and delve into the dictionary in Swift. Dictionary is a container which stores key-value pairs. All the keys in the dictionary are of the same type and all the values are of the same type. The order in the dictionary is not maintained. If you are a Java developer, you can correlate this to a Hashtable which gives fast access to its entries.

Defining a Dictionary

A dictionary is a comma separated key-value pair and defining such a dictionary literal is simple. Let us see the following example:

let person = ["firstname":"John", "lastname":"Doe", "location":"Texas"]

Here, notice that I have used the keyword let which creates an immutable dictionary. To create a mutable dictionary, just use the var keyword.

var person = ["firstname":"John", "lastname":"Doe", "location":"Texas"]

In the above examples, the compiler automatically identifies the type of keys and values. In this case, it is a string since we have used strings. Suppose we want to create an empty dictionary — we'd need to tell the compiler about types as follows:

var sample1 = [String:String]()
var sample2 = [Int:String]()
var sample2 = [Int:CustomObject]()

Reading Dictionary Values

If we want to read a value based on its key, we need to use subscript syntax.

let person = [“firstname”:”John”, “lastname”:”Doe”, “location”:”Texas”]

var value = person[“firstname”]

This should output the string "John".

Checking If Dictionary Empty

We can check whether the dictionary is empty by using the following syntax.

let person = ["firstname":"John", "lastname":"Doe", "location":"Texas"] 
var value = person.IsEmpty

This returns false as it contains three items in the dictionary.

Update a Value in a Dictionary

The values in a dictionary can be updated using their keys in two methods.

Method 1

var person = ["firstname":"John", "lastname":"Doe", "location":"Texas"] person["firstname"] = "Jane"

This updates the value of the first key-value pair.

Method 2

var updatedValue = person.updateValue["Jane", forKey: "firstname"]

The variableupdatedValue would contain the string "Jane".

Adding and Removing a Key-Value Pair

We can add or remove a key-value pair easily to a dictionary. We can use either subscript syntax or the updateValue(_:, forKey:) method.

Add

var person = ["firstname":"John", "lastname":"Doe", "location":"Texas"] 
person["occupation"] = "Technician"

This just adds a new entry to the above dictionary.

var updatedDictionary = person.updateValue("Technician", forKey: "occupation"]

Here, the variable  updatedDictionary would be set to nil because there is no value associated with the key "occupation".

Remove

var person = ["firstname":"John", "lastname":"Doe", "location":"Texas"] 
person["location"] = nil

This will remove the  location key-value pair.

We can also remove the key-value pair using removeValue(forKey:).

var updatedDictionary = person.removeValue(forKey:"location")

The location key-value pair would be removed. The variable updatedDictionary would contain the value "Texas".

If we would like to remove all the entries in dictionary, we can simply remove them as follows:

person.removeAll()

Counting in a Dictionary

The size of the dictionary can be obtained by calling the count property.

var person = ["firstname":"John", "lastname":"Doe", "location":"Texas"] 
var count = person.count

This gives the count 3.

Conclusion

We just covered the basics of a dictionary in Swift. A detailed documentation can be found on the Apple Developer site.

I hope you enjoyed my article. Feel free to leave any comments or suggestions.

Happy learning!

Dictionary (software) Swift (programming language)

Published at DZone with permission of Swathi Prasad, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • PHP vs React
  • Spring Cloud: How To Deal With Microservice Configuration (Part 1)
  • Writing a Modern HTTP(S) Tunnel in Rust
  • Why Open Source Is Much More Than Just a Free Tier

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: