Skip to content

Instantly share code, notes, and snippets.

@austinzheng
Last active March 7, 2016 20:41
Show Gist options
  • Star 25 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save austinzheng/8fda3f61e1fd06383928 to your computer and use it in GitHub Desktop.
Save austinzheng/8fda3f61e1fd06383928 to your computer and use it in GitHub Desktop.
Anonymous class experiment in Swift
import Foundation
protocol SomeDelegateProtocol : class {
func firstFunc() -> String
func secondFunc() -> Bool
func thirdFunc() -> Self
}
class MyClass {
weak var delegate : SomeDelegateProtocol?
}
class Parent {
var child : MyClass
var strongDelegate : SomeDelegateProtocol? = nil
func setup() {
strongDelegate = {
// [self] // Original version had this not commented; it's commented to let people know it was a typo
final class SomethingClass : SomeDelegateProtocol {
func firstFunc() -> String { return "foo" }
func secondFunc() -> Bool { return true }
func thirdFunc() -> SomethingClass { return SomethingClass() }
}
return SomethingClass()
}()
child.delegate = strongDelegate
}
init() {
self.child = MyClass()
self.setup()
}
}
var bleh = Parent()
var result = bleh.child.delegate?.firstFunc()
// selfResult is inferred to be type 'Optional<SomethingDelegateProtocol>'.
let selfResult = bleh.child.delegate?.thirdFunc()
println("Got \(result!)")
@jameswomack
Copy link

What does [self] achieve here?

@austinzheng
Copy link
Author

Nothing much, my mistake! I adapted this gist from an earlier private version that was originally written for one of the early Xcode betas, and I had to make a few changes to get it working, but I was in a hurry. I modified the gist to make it a bit clearer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment