Swift .mapValues()
Published Oct 7, 2024
Contribute to Docs
In Swift, the .mapValues() method transforms the values of a dictionary while keeping the keys unchanged. This method is part of the Dictionary structure and is useful for modifying or mapping only the values without altering the keys. This method returns a new dictionary with the same keys but with values transformed based on the provided closure, leaving the original dictionary unmodified.
Syntax
dictionaryName.mapValues ({ transform })
dictionaryName: The instance of aDictionarywhose values are to be transformed.transformation: A closure that defines how each value in the dictionary should be transformed.
Example
In the following example, the mapValues() method is used to increase each student’s grade by 10 points while keeping the keys unchanged in the studentGrades dictionary:
var studentGrades = ["Jon": 65, "Nic": 77, "Mary": 80]// Increase each student's grade by 10 pointslet updatedGrades = studentGrades.mapValues { grade ingrade + 10}print(updatedGrades)
The output for the above code is:
["Jon": 75, "Nic": 87, "Mary": 90]
In this example, mapValues() increases each grade by 10 points, while the keys ("Jon", "Nic", and "Mary") remain unchanged.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Swift on Codecademy
- Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
- Includes 7 Courses
- With Certificate
- Beginner Friendly.13 hours
- A powerful programming language developed by Apple for iOS, macOS, and more.
- Beginner Friendly.12 hours