Bhavuk Jain
Bhavuk Jain

Reputation: 2187

Creating a Mutable Dictionary in Swift

I want to create a mutable dictionary which I can pass it to another controller so that both the dictionaries in different controllers points to the same memory location. If I change the value at another controller, it is also reflected in the previous controller. This trick used to work fine with NSMutableDictionary without using any delegates.

My dictionary is of type: [String:AnyObject]

Upvotes: 0

Views: 964

Answers (2)

Scott Thompson
Scott Thompson

Reputation: 23701

Swift's dictionary types are value types whereas your old NSMutableDictionary instances are reference types.

There is nothing that says you HAVE to use Swift's value types in the place of your old dictionary. If you have a good reason for using reference semantics with the dictionary, go ahead and leave it as an NSMutableDictionary and use the methods of that class to manipulate it. Just note in your code that you are using NSMutableDictionary explicitly because you want the reference semantics.

Upvotes: 0

Tommy
Tommy

Reputation: 100612

Swift collections are value types, not reference types and although you can pass value types by reference, that lasts only for the lifetime of the call.

What you're doing would be considered bad design — objects are sovereign, with well-defined interfaces, and encapsulated state; they do not informally pool state.

What you probably need to do is take your shared state, formalise an interface to it, and move it to your model. Each controller can separately talk to your model.

Upvotes: 2

Related Questions