Created
August 8, 2018 05:47
-
-
Save codeOfRobin/1516b1a2d3ee35b26880dd59964de90c to your computer and use it in GitHub Desktop.
A reimplementation of the ideas in https://twitter.com/dmcrodrigues/status/1013851414467051525
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: [Previous](@previous) | |
import Foundation | |
class DummyAtomic<Value> { | |
var value: Value | |
init(_ value: Value) { | |
self.value = value | |
} | |
func modify<Result>(_ action: (inout Value) -> Result) -> Result { | |
return action(&value) | |
} | |
} | |
//// Suppose we're trying to use a closure that takes a string and "doubles" it. We also need to log how many characters we "process" by adding the number of characters in the string to the counter. Now, since DummyAtomic(0) is being captured in the closure, we can't mess with it outside of the closure. | |
//// One problem tho: 🤔. How tf do you access teh counter outside of the closure? | |
let closure: (String) -> String = { [counter = DummyAtomic(0)] | |
string in | |
return counter.modify({ (count) in | |
count += string.count | |
print(counter.value) | |
return string + string | |
}) | |
} | |
print(closure("something")) | |
print(closure("robin")) | |
print("something".count + "robin".count) | |
//: [Next](@next) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment