Skip to content

Instantly share code, notes, and snippets.

@wildthink
Last active March 28, 2016 17:28
Show Gist options
  • Save wildthink/48cce4cd2f27695ebb08 to your computer and use it in GitHub Desktop.
Save wildthink/48cce4cd2f27695ebb08 to your computer and use it in GitHub Desktop.
NSBlockInit offers a Swift extension to the initialization protocols so you can easily chain a setup block as part of the basic init() are by using setup(Self) chained onto the init.
//
// NSBlockInit.swift
// XjSwiftLab
//
// Created by Jason Jobe on 3/19/16.
// Copyright (c) 2016 Jason Jobe. All rights reserved.
// https://gist.github.com/wildthink/48cce4cd2f27695ebb08
//
// Thanks to Mike Ash for his expertise and support of the community
// https://www.mikeash.com/pyblog/friday-qa-2015-12-25-swifty-targetaction.html
// Example usage
// let button = NSButton() {
// $0.title = "Hello World"
// }
//
import Foundation
protocol NSObjectBlockInitProtocol {}
extension NSObjectBlockInitProtocol where Self: NSObject
{
init (setup: (Self) -> Void) {
self.init()
setup(self)
}
func setup(setup: (Self) -> Void) -> Self {
setup(self)
return self
}
}
extension NSObject: NSObjectBlockInitProtocol {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment