Skip to content

Instantly share code, notes, and snippets.

@pofat
Last active November 7, 2018 12:43
Show Gist options
  • Save pofat/c200525f3d6c32be71e323e82f478335 to your computer and use it in GitHub Desktop.
Save pofat/c200525f3d6c32be71e323e82f478335 to your computer and use it in GitHub Desktop.
Better way to do initialization in Swift
// From https://github.com/devxoul/Then/blob/master/Sources/Then/Then.swift
// It's easy to move them into your codebase
import Foundation
public protocol Then {}
extension Then where Self: Any {
/// Makes it available to set properties with closures just after initializing.
///
/// let label = UILabel().then {
/// $0.textAlignment = .Center
/// $0.textColor = UIColor.blackColor()
/// $0.text = "Hello, World!"
/// }
public func then(@noescape block: inout Self -> Void) -> Self {
var copy = self
block(&copy)
return copy
}
/// Makes it available to set properties with closures just after initializing and copying the value types.
///
/// let frame = CGRect().with {
/// $0.origin.x = 10
/// $0.size.width = 100
/// }
public func with(_ block: (inout Self) throws -> Void) rethrows -> Self {
var copy = self
try block(&copy)
return copy
}
}
extension Then where Self: AnyObject {
/// Makes it available to set properties with closures just after initializing.
///
/// let label = UILabel().then {
/// $0.textAlignment = .Center
/// $0.textColor = UIColor.blackColor()
/// $0.text = "Hello, World!"
/// }
public func then(@noescape block: Self -> Void) -> Self {
block(self)
return self
}
}
extension NSObject: Then {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment