THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
This tutorial explains how to check the key and value that exists in a Dictionary in Swift.
Dictionary is a data storage in swift to store keys and values.
Let’s declare a dictionary with a key of Int and a value of String
let emp: [Int: String] = [1: "john", 2: "franc", 3: "andrew"]
In Swift, Dictionary[key] returns Optional value if exists else returns nil.
emp[11] != nil returns true if key exists in dictionary, else return false, not exists in dictionary
import Foundation;
let emp: [Int: String] = [1: "john", 2: "franc", 3: "andrew"]
// check key 11 exists in Dictionary
let keyExists = emp[11] != nil
print(keyExists)
if(keyExists ){
print("Key 11 not exists in Dictionary")
}
// check key 1 exists in Dictionary
let keyExists1 = emp[1] != nil
print(keyExists1)
if(keyExists1 ){
print("Key 1 exists in Dictionary")
}
Output:
false
true
Key 1 exists in Dictionary
dictionary. values return the list of values, call contains the method to check if the value exists or not.
It returns true if a value exists, else returns false.
Here is an example to check if the dictionary contains a value or not in swift.
import Foundation;
let emp: [Int: String] = [1: "john", 2: "franc", 3: "andrew"]
print(emp.values.contains("john")) // true
print(emp.values.contains("john1")) // false
Output:
true
false
🧮 Tags
Recent posts
Puppeteer Login Test example How to convert Double to Integer or Integer to double in Dart| Flutter By Example Best ways to fix 504 gateway time out in nodejs Applications Fix for Error No configuration provided for scss Multiple ways to List containers in a Docker with examplesRelated posts