Skip to content

Instantly share code, notes, and snippets.

@akisute
Last active August 29, 2015 14:02
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 akisute/9b598cc8de998096548a to your computer and use it in GitHub Desktop.
Save akisute/9b598cc8de998096548a to your computer and use it in GitHub Desktop.
Several disappointing Swift code snippets...
class MyClass {
var someValue:Int
func someMethod() -> Int {
return 42
}
var callback:(Int) -> (Void) = {(value:Int) -> (Void) in
// Using self within a closure owned by self makes reference loop
self.someValue = self.someMethod() + value
}
}
class MyClass {
var someValue:Int
func someMethod() -> Int {
return 42
}
var callback:(Int) -> (Void) = {[unowned self] (value:Int) -> (Void) in
// self is specified as unowned in closure capture list [unowned self],
// so the following self is now unowned by this closure!
self.someValue = self.someMethod() + value
// By the way, cannot directly use variables and methods without self
// (the following code is compiler error)
/*
someValue = someMethod() + value
*/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment