Last active
April 23, 2024 14:26
-
-
Save macserv/6560df941ef3bf141183f23437f29223 to your computer and use it in GitHub Desktop.
Swift "Configuration" Operator
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
// | |
// ConfigurationOperator.swift | |
// | |
// Created by Matthew L. Judy on 2024/3/21. | |
// | |
/// Configuration Operator: | |
/// Provides an expressive way to instantiate, configure, and assign an object | |
/// in a single perceived step, reducing the boilerplate necessary to achieve | |
/// the same outcome using traditional closure-based assignment. | |
/// | |
/// - Example: ``DateFormatter`` | |
/// ``` | |
/// // Configure DateFormatter using Configuration operator: | |
/// let iso8601A = ISO8601DateFormatter() <| { $0.formatOptions = [.withFullDate, .withDashSeparatorInDate] } | |
/// | |
/// // Configure DateFormatter using traditional closure: | |
/// let iso8601B: ISO8601DateFormatter = { | |
/// let formatter = ISO8601DateFormatter() | |
/// formatter.formatOptions = [.withFullDate, .withDashSeparatorInDate] | |
/// return formatter | |
/// }() | |
/// ``` | |
/// - Example: ``Calendar`` | |
/// ``` | |
/// // Configure Calendar using Configuration operator: | |
/// let calendarA = Calendar.current <| { $0.timeZone = TimeZone(identifier: "UTC")! } | |
/// | |
/// // Configure Calendar using traditional closure: | |
/// let calendar: Calendar = { | |
/// let calendar = Calendar.current | |
/// calendar.timeZone = TimeZone(identifier: "UTC")! | |
/// return calendar | |
/// }() | |
/// ``` | |
/// | |
infix operator <| : AssignmentPrecedence | |
func <| <Subject: Any> (subject: Subject, modifier: ((inout Subject) -> Void)) -> Subject | |
{ | |
var subject = subject | |
modifier(&subject) | |
return subject | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment