Last active
March 7, 2016 20:41
-
-
Save austinzheng/8fda3f61e1fd06383928 to your computer and use it in GitHub Desktop.
Anonymous class experiment in Swift
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
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!)") |
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
What does
[self]
achieve here?