Skip to content

Create memory-swift #16

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions memory-swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import Foundation

final class SharedPoint {
private var x: Int32
private var y: Int32
private let lock = DispatchQueue(label: "sharedpoint-queue")

init(x: Int32, y: Int32) {
self.x = x
self.y = y
}

func move(dx: Int32, dy: Int32) {
lock.sync {
x &+= dx
y &+= dy
}
}

func clone() -> SharedPoint {
return lock.sync {
return SharedPoint(x: x, y: y)
}
}

func toString() -> String {
return lock.sync {
return "(\(x), \(y))"
}
}
}

let p1 = SharedPoint(x: 10, y: 20)
print(p1.toString()) // (10, 20)

let c1 = p1.clone()
c1.move(dx: -5, dy: 10)
print(c1.toString()) // (5, 30)