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
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] ?? []