Skip to content

Instantly share code, notes, and snippets.

View deadlock.swift
class Account: NSObject {
var balance: Double
var id: Int
override init(id: Int, balance: Double) {
self.id = id
self.balance = balance
}
func withdraw(amount: Double) {
View memoryBarriersWithSync.swift
//Processor #1:
while f == 0 {
OSMemoryBarrier()
print x
}
//Processor #2:
x = 42
OSMemoryBarrier()
f = 1
View memoryBarriers.swift
//Processor #1:
while f == 0 {
print x
}
//Processor #2:
x = 42
f = 1
View raceCondition.swift
var x = 100
func calculate() {
var y = 0
for i in 1...1000 {
y += i
}
x = y
}
View concurrentPrintDispatchQueue.swift
var title : [String] = []
func write(_ text: String) {
let words = text.split(separator: " ")
DispatchQueue.main.async {
for word in words {
title.append(String(word))
print(word)
}
}
View concurrentPrintLock.swift
var title : [String] = []
var lock = NSLock()
func write(_ text: String) {
let words = text.split(separator: " ")
lock.lock()
for word in words {
title.append(String(word))
print(word)
}
View concurrentprint.swift
func write(_ text: String) {
let words = text.split(separator: " ")
for word in words {
title.append(String(word))
}
}
write("Concurrency with Swift:") // Thread 1
write("What could possibly go wrong?") // Thread 2
View indexloop.swift
var messages: [Message] = []
func dispatch(_ message: Message) {
messages.append(message)
dispatchToPlugins()
}
func dispatchToPlugins() {
while messages.count > 0 {
for plugin in plugins {
View siriPhrases.swift
if let shortcut = voiceShortcutDataManager?.voiceShortcut(for: order) {
let editVoiceShortcutViewController = INUIEditVoiceShortcutViewController(voiceShortcut: shortcut)
editVoiceShortcutViewController.delegate = self
present(editVoiceShortcutViewController, animated: true, completion: nil)
}
else {
if let shortcut = INShortcut(intent: order.intent) {
let addVoiceShortcutVC = INUIAddVoiceShortcutViewController(shortcut: shortcut)
addVoiceShortcutVC.delegate = self
present(addVoiceShortcutVC, animated: true, completion: nil)
View intentResponses.swift
public func confirm(intent: DanceIntent, completion: @escaping (DanceIntentResponse) -> Void) {
// Do Stuff
completion(DanceIntentResponse(code: .play, userActivity: nil))
}
public func handle(intent: DanceIntent, completion: @escaping (DanceIntentResponse) -> Void) {
// Do Stuff
completion(DanceIntentResponse.success(dance: dance, playTime: 10))
}