Skip to content

Instantly share code, notes, and snippets.

@natebird
Created January 6, 2016 18:42
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 natebird/1e1364aa86e83635dded to your computer and use it in GitHub Desktop.
Save natebird/1e1364aa86e83635dded to your computer and use it in GitHub Desktop.
Implementing the Ruby memoization operator ||= in Swift
//: Implementing Ruby's memoization operator in Swift
// From: https://airspeedvelocity.net/2014/06/10/implementing-rubys-operator-in-swift/
// define operator properties
infix operator ||= {
associativity right
precedence 90
assignment
}
// define the operator function
// Using generic to apply to all types
func ||=<T>(inout lhs: T?, @autoclosure rhs: () -> T) {
if(lhs == nil) {
lhs = rhs()
}
}
// This was in the post to address something with boolean values
// but it seems to work regardless
//func ||=<T: BooleanType>(inout lhs: T, @autoclosure rhs: () -> T) {
// if(!lhs) {
// lhs = rhs()
// }
//}
var s: String?
s ||= "First assignment"
s ||= "Second assignment"
assert(s == "First assignment")
var n: Int?
n ||= 5
n ||= 6
assert(n == 5)
var t: Bool?
t ||= true
t ||= false
assert(t == true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment