Last active
February 17, 2025 13:20
-
-
Save PimCoumans/d6ca254c6eb6199ba89e80f022f6db14 to your computer and use it in GitHub Desktop.
Easier initializer with special infix operator
This file contains hidden or 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 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