Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share a Dictionary instance in Swift?

According to the Swift Programming Language reference, Dictionary instances are copied whenever they are passed to a function/method or assigned to a constant or variable. This seems inefficient. Is there a way to efficiently share the contents of a dictionary between two methods without copying?

like image 248
Greg Brown Avatar asked Jun 03 '14 20:06

Greg Brown


1 Answers

It's true the documentation says that but there are also various notes saying it won't affect the performance. The copying will be performed lazily - only when needed.

The descriptions below refer to the “copying” of arrays, dictionaries, strings, and other values. Where copying is mentioned, the behavior you see in your code will always be as if a copy took place. However, Swift only performs an actual copy behind the scenes when it is absolutely necessary to do so. Swift manages all value copying to ensure optimal performance, and you should not avoid assignment to try to preempt this optimization.

Source: Classes & Collections

Meaning - don't try to optimize before you actually encounter performance problems!

Also, don't forget that dictionaries are structures. When you pass them into a function, they are implicitly immutable, so no need for copying. To actually pass a mutable dictionary into a function, you can use an inout parameter and the dictionary won't be copied (passed by reference). The only case when a mutable dictionary passed as a parameter will be copied is when you declare the parameter as var.

like image 85
Sulthan Avatar answered Sep 22 '22 11:09

Sulthan