Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Dec 19, 2014

What does [self] achieve here?

@austinzheng

This comment has been minimized.

Copy link
Owner Author

commented Dec 19, 2014

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
You can’t perform that action at this time.