2/06/2024

iOS swift dictionary example code

 .


// Existing dictionary of ages

var ages: [String: Int] = ["John": 30, "Emma": 25]


// Adding a new dictionary with String keys and String values

var occupations: [String: String] = ["John": "Engineer", "Emma": "Doctor"]


// Adding a new key-value pair to the occupations dictionary

occupations["Mike"] = "Teacher"


// Updating a value for a key in the occupations dictionary

occupations["Emma"] = "Senior Doctor" // Emma got a promotion!


// Accessing a value for a given key in the occupations dictionary

if let occupation = occupations["John"] {

    print("John's occupation is \(occupation).")

} else {

    print("John's occupation is not available.")

}


// Merging the ages and occupations dictionaries

// Assuming you want to create a summary for each person

for (name, age) in ages {

    if let occupation = occupations[name] {

        print("\(name) is \(age) years old and works as a \(occupation).")

    } else {

        print("\(name) is \(age) years old.")

    }

}


// Removing a key-value pair from the occupations dictionary

occupations["Mike"] = nil // Mike's occupation is removed


// Iterating over all key-value pairs in the occupations dictionary

for (name, occupation) in occupations {

    print("\(name) works as a \(occupation).")

}


// Checking the count of elements in both dictionaries

print("There are \(ages.count) people in the ages dictionary.")

print("There are \(occupations.count) occupations listed.")

..


refer to code, hope to get some useful idea.

Thank you.

๐Ÿ™‡๐Ÿป‍♂️

No comments:

Post a Comment