Convert dictionary values to a different type in Swift

swift dictionary
swift dictionary keys
convert dictionary to string in swift
swift dictionary get key for value
swift dictionary map to dictionary
how to get value from array of dictionary in swift
convert array of dictionary to string swift
swift map one dictionary to another

I have have a dictionary. I would like to go through it and convert the values to a different type. .map{ } would be perfect except this is a dictionary and not an array. So, I found a mapPairs function on stack overflow that should work for dictionaries. Unfortunately I get a conversion error.

extension Dictionary {
    //    Since Dictionary conforms to CollectionType, and its Element typealias is a (key, value) tuple, that means you ought to be able to do something like this:
    //
    //    result = dict.map { (key, value) in (key, value.uppercaseString) }
    //
    //    However, that won't actually assign to a Dictionary-typed variable. THE MAP METHOD IS DEFINED TO ALWAYS RETURN AN ARRAY (THE [T]), even for other types like dictionaries. If you write a constructor that'll turn an array of two-tuples into a Dictionary and all will be right with the world:
    //  Now you can do this:
    //    result = Dictionary(dict.map { (key, value) in (key, value.uppercaseString) })
    //
    init(_ pairs: [Element]) {
        self.init()
        for (k, v) in pairs {
            self[k] = v
        }
    }

    //    You may even want to write a Dictionary-specific version of map just to avoid explicitly calling the constructor. Here I've also included an implementation of filter:
    //    let testarr = ["foo" : 1, "bar" : 2]
    //    let result = testarr.mapPairs { (key, value) in (key, value * 2) }
    //    result["bar"]
    func mapPairs<OutKey: Hashable, OutValue>(@noescape transform: Element throws -> (OutKey, OutValue)) rethrows -> [OutKey: OutValue] {
        return Dictionary<OutKey, OutValue>(try map(transform))
    }

}

var dict1 = ["a" : 1, "b": 2, "c": 3]

let convertedDict: [String: String] = dict1.mapPairs { // ERROR: cannot convert value of type '_ -> (String, Int)' to expected argument type '(String, Int) -> (String, String)'
    element -> (String, Int) in
        element[0] = String(element.1)
        return element
}

As the example given by the method block, you should use mapPairs like this:

let convertedDict: [String: String] = dict1.mapPairs { (key, value) in
    (key, String(value))
}

Note, since Swift supports implicit inference, you don't need explicitly return.

How to transform a dictionary using mapValues(), This extra method is useful because dictionaries can't have duplicate keys, but if you're only transforming the values from a dictionary then this� Swift 4 allows you to create grouping of Dictionary values. var cities = ["Delhi","Bangalore","Hyderabad","Dehradun","Bihar"] You can use the following simple syntax to group the values of dictionary according to first alphabet. var GroupedCities = Dictionary (grouping: cities) { $0.first!


If you want to change a dict of [String: Int] to [String: String], you can pretty much do the same as my previous answer:

let dict1 = ["a" : 1, "b": 2, "c": 3]
var dict2 = [String: String]()

dict1.forEach { dict2[$0.0] = String($0.1) }

print("\(dict2.dynamicType): \(dict2)")

Output:

Dictionary<String, String>: ["b": "2", "a": "1", "c": "3"]

How to convert Dictionary to Arrays of Keys and Values in Swift , The type of keys array is same as that of keyType , and the type of values array is same as that of valueType . Example – Get Key and Value arrays from Swift� Welcome to Swift Tutorial. In this tutorial, we will learn how to create a dictionary with (key, value) pairs in Swift programming. Dictionaries are used to store a collection of (key, value) pairs. In a dictionary, you can only insert (key, value) pairs whose key is unique in the dictionary. Dictionary can be created in two ways. They are: Create an empty Dictionary To create an empty


In Swift 5 and later:

let originalDict: [TypeA: TypeB] = /* */
let convertedDict: [TypeA: TypeC] = originalDict.mapValues { /* conversion here */ }

Example:

let integerDict: [String: Int] = ["a": 1, "b": 2]
let doubleDict: [String: Double] = integerDict.mapValues(Double.init)

print(doubleDict) // ["a": 1.0, "b": 2.0]

Dictionary, For bridging to be possible, the Key and Value types of a dictionary must be classes, on the dictionary to get an immutable copy and then performs additional Swift bookkeeping work Converting Between Dictionaries and Create ML Types. In this tutorial, we will learn how to iterate through (key, value) pairs of Dictionary in Swift and print them. To iterate over (key, value) pairs of a Dictionary, use for loop. You can also access the index of the (key, value) paris using the enumerated Dictionaries. Example to iterate a Dictionary in Swift


I don't know if this might help, but since Swift 4.2 there is a new operator called mapValues(_:) (https://developer.apple.com/documentation/swift/dictionary/2995348-mapvalues), which would transform the result you are looking for to:

let convertedDict = dict1.mapValues { String($0) }

map(_:), Swift Standard Library sequence as its parameter and returns a transformed value of the same or of a different type. In this example, map is used first to convert the names in the array to lowercase strings Returns a new dictionary containing the keys of this dictionary with the values transformed by the given closure. All of Swift’s basic types (such as String, Int, Double, and Bool) are hashable by default, and can be used as set value types or dictionary key types. Enumeration case values without associated values (as described in Enumerations) are also hashable by default.


Swift - Dictionaries, Swift 4 puts strict checking which does not allow you to enter a wrong type i. Swift 4 allows you to create Dictionary from arrays (Key-Value Pairs.) updateValue("New value of one", forKey: 1) var someVar = someDict[1] print( " Old value of key = 1 is \(oldVal)" ) print( "Value of key = 1 is \(someVar)" Convert to Arrays. Type casting in Swift is implemented with the is and as operators. These two operators provide a simple and expressive way to check the type of a value or cast a value to a different type. You can also use type casting to check whether a type conforms to a protocol, as described in Checking for Protocol Conformance.


Dictionary and Set Improvements in Swift 4.0, This post explores these new transformations, using some grocery data struct, made up of a name and a department, will serve as the data type: You can transform the values of a dictionary, while keeping the same keys,� Any type that conforms to the Hashable protocol can be used as a dictionary’s Key type, including all of Swift’s basic types. You can use your own custom types as dictionary keys by making them conform to the Hashable protocol. Getting and Setting Dictionary Values. The most common way to access values in a dictionary is to use a key as a


Swift Dictionary Examples, In Swift, a Dictionary is a primary collection type. Here we create another String key, Int value dictionary. But they can easily be converted into arrays. Value types do not suffer from this overhead, leading to efficient instance creation and copying. Copies of value types are said to be cheap because value type instances can be copied in constant time. Swift implements built-in extensible data structures such as String, Array, Dictionary, etc., as value types. However, these cannot be allocated