[swift-users] Recommendation for thread-safe dictionary

Howard Lovatt howard.lovatt at gmail.com
Thu Dec 10 19:24:43 CST 2015


I would do something like:

    import Foundation

    class Task { // Must be a class to prevent Swift copy semantics
eliminating the result

        private static let queue = dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_HIGH, 0)

        private let group = dispatch_group_create()

        private var _result: String?

        init(name: String) {

            dispatch_group_async(group, Task.queue) {

                self._result = name // The asynchronous task!

            }

        }

        var result: String { // Provide safe access to result

            dispatch_group_wait(group, DISPATCH_TIME_FOREVER) // Block
until task finished

            return _result!

        }

    }


    var tasks = [String : Task]()

    let names = ["One", "Two"]

    names.forEach {

        tasks[$0] = Task(name: $0)

    }

    tasks.map { (_, task) in // Prints [One, Two] in playground

        task.result

    }

On 11 December 2015 at 07:02, Dmitri Gribenko via swift-users <
swift-users at swift.org> wrote:

> On Thu, Dec 10, 2015 at 11:20 AM, Jens Alfke <jens at mooseyard.com> wrote:
> > All we’re saying is that a class like this isn’t commonly useful enough
> to go into a library.
>
> And too easy to misuse if provided.
>
> Dmitri
>
> --
> main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
> (j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>



-- 
  -- Howard.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20151211/fa6e4ea3/attachment.html>


More information about the swift-users mailing list