David.C
David.C

Reputation: 456

Map array of objects to Dict with key as Enum

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

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

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

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] 

Upvotes: 0

Views: 466

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236420

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 accomplish is to group all monthly subscriptions which can be done 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] ?? []

Upvotes: 2

Related Questions