Skip to content

Instantly share code, notes, and snippets.

@brennanMKE
Last active October 4, 2018 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brennanMKE/1fc5ba519ea5bacfe9e44ab2c641ca2f to your computer and use it in GitHub Desktop.
Save brennanMKE/1fc5ba519ea5bacfe9e44ab2c641ca2f to your computer and use it in GitHub Desktop.
Synchronized Map and Array

Synchronized Map and Array

Dispatch is often used to protect a property when operating with concurrent behavior. A DispatchQueue can be used to ensure that a property is protected by using the sync function as demonstrated in the sample code below.

import Foundation
class SynchronizedArray<Value> {
private let queue = DispatchQueue(label: "SynchronizedArray")
private var array = [Value]()
func find(at index: Int) -> Value? {
return queue.sync {
guard index < array.count else {
return nil
}
return array[index]
}
}
func add(item: Value) {
queue.sync {
array.append(item)
}
}
func remove(at index: Int) {
queue.sync {
array.remove(at: index)
}
}
}
import Foundation
class SynchronizedMap<Key, Value> where Key : Hashable {
private let queue = DispatchQueue(label: "SynchronizedMap")
private var map = [Key:Value]()
func find(key: Key) -> Value? {
return queue.sync {
return map[key]
}
}
func add(key: Key, item: Value) {
queue.sync {
map[key] = item
}
}
func remove(key: Key) {
queue.sync {
map[key] = nil
}
}
}
struct Person {
let name: String
}
extension Person: CustomStringConvertible {
var description: String {
return name
}
}
var peopleMap = SynchronizedMap<String, Person>()
peopleMap.add(key: "Tim", item: Person(name: "Tim Cook"))
peopleMap.add(key: "Jony", item: Person(name: "Jony Ive"))
peopleMap.add(key: "Lisa", item: Person(name: "Lisa Jackson"))
peopleMap.find(key: "Tim")
peopleMap.find(key: "Jony")
peopleMap.find(key: "Eddy")
peopleMap.find(key: "Lisa")
var peopleArray = SynchronizedArray<Person>()
peopleArray.add(item: Person(name: "Tim Cook"))
peopleArray.add(item: Person(name: "Jony Ive"))
peopleArray.add(item: Person(name: "Lisa Jackson"))
peopleArray.find(at: 0)
peopleArray.find(at: 1)
peopleArray.find(at: 3)
peopleArray.find(at: 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment