Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Map array of objects to Dict with key as Enum

I got a dict of of enum as key and values as object

enum SubscriptionType {
        case monthly = "uniqueID"
        case annualy = "uniqueID"
    }

 @Published var subscriptionProducts = [SubscriptionType: SKProduct]()

I got another array of type SKProduct
I want to assign it to my dict with a property of each object as key, and the object itself as value

Trying

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 subscriptionProducts = Dictionary(uniqueKeysWithValues:products.map({$0.productIdentifier , $0 }))

But I got
Type of expression is ambiguous without more context

the productIdentifier is of type String, how to assign it to the rawValue of my enum?

The result I want to achieve later is to get the specific object using that key

   let monthlySubscriptionProduct = subscriptionProducts[.monthly] 

>Solution :

You need to first declare your SubscriptionType enumeration RawValue as String. Then you will need to convert your productIdentifier String value to SubscriptionType using its fallible init(rawValue:) initializer. Something like:

enum SubscriptionType: String {
    case monthly, annualy
}

let subscriptionProducts: [SubscriptionType: SKProduct] = Dictionary(uniqueKeysWithValues: products.compactMap {
    guard let subscriptionType = SubscriptionType(rawValue: $0.productIdentifier) else {
        return nil
    }
    return (subscriptionType, $0)
})
let monthlySubscriptionProduct = subscriptionProducts[.monthly]

But IMO that’s not what you really want. Looks like what you are trying to achieve is to group all monthly subscriptions which you can achieve using reduce as follow:

let subscriptionProducts: [SubscriptionType: [SKProduct]] = products.reduce(into: [:]) {
    guard let subscriptionType = SubscriptionType(rawValue: $1.productIdentifier) else {
        return
    }
    $0[subscriptionType, default: []].append($1)
}

let monthlySubscriptions = subscriptionProducts[.monthly] ?? []
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading