Swift: mutate cast parameter (Error: Cannot use mutating member on immutable value of type 'MyObjectType' (aka 'Dictionary<Int, Int>')

90 views Asked by At

I have a functions where I passed in Dictionary [Int : Int] as inout T and would need to write into the Dictionary. This function is included as a function of a protocol.

However, after casting T into MyObjectType (Dictionary), it becomes immutable.

Question: How can I make a generic parameter (it can be passed in as struct, class, array or dictionary) mutable after casting?

typealias MyObjectType = [Int : Int] // Key is a enum with Int as RawValue

static func myGenericFunction<T>(_ object: inout T) {    
    (object as! MyObjectType).updateValue(0, forKey: 1)    
}

I have tried casting it to NSMutableDictionary as below which compile successfully but crash when running with simulator.

(object as! NSMutableDictionary)[Int(pMetric.selectedUnit)] = Int(pMetric.metricType)

Thanks for any good solution!

0

There are 0 answers