Yurkevich
Yurkevich

Reputation: 4517

Swift Dictionary in Objective-C as NSMutableDictionary

In my Swift class I have :

class Model : NSObject {

    var localSettings = Dictionary<String, NSNumber>()

    class var sharedInstance: Model {
        struct Singleton {
            static let instance = Model()
        }

        return Singleton.instance
    }
}

I call my new Swift model class from Objective-C class. I have no problems reading local settings dictionary but when I try to modify it:

self.model.localSettings[@"Key"] = @1;

I am getting compile error:

Expected method to write dictionary element not found on object of type 'NSDictionary<NSString *,NSNumber *> *'

I am using Xcode 8 and Swift 2.3

Upvotes: 3

Views: 945

Answers (1)

EmilioPelaez
EmilioPelaez

Reputation: 19882

Whenever you modify a dict/array in Swift, the setter gets called again, this wouldn't happen on ObjC if you added a new element to the collection, I think that's why mutable collections are bridged to their immutable equivalent.

You could create a mutable copy, modify it, and set it to the property, but that would be pretty verbose, I think a better solution would be to add methods to Model that modify the settings dictionary.

Upvotes: 2

Related Questions