Skip to content

Instantly share code, notes, and snippets.

@PimCoumans
Last active February 17, 2025 13:20
Show Gist options
  • Save PimCoumans/d6ca254c6eb6199ba89e80f022f6db14 to your computer and use it in GitHub Desktop.
Save PimCoumans/d6ca254c6eb6199ba89e80f022f6db14 to your computer and use it in GitHub Desktop.
Easier initializer with special infix operator
import Foundation
protocol ClosureConfigurable { }
extension ClosureConfigurable {
typealias Configurator = (Self) throws -> Void
/// Configures the receiver with a closure that is executed with `Self` as a parameter
/// - Parameter configurator: Closure executed immediately with `Self` as a parameter
/// - Returns: Instance after closure is applied
@discardableResult public func setup(with configurator: Configurator) rethrows -> Self {
try configurator(self)
return self
}
}
infix operator .. : AssignmentPrecedence
extension ClosureConfigurable {
/// Typical usage:
/// ```
/// lazy var customView = MyCustomView() .. {
/// $0.backgroundColor = .systemPurple
/// }
/// ```
/// - Returns: Instance after closure is applied
public static func .. (value: Self, closure: Configurator) rethrows -> Self {
try value.setup(with: closure)
}
}
extension NSObject: ClosureConfigurable { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment