Skip to content

Instantly share code, notes, and snippets.

@mwaterfall
Created January 28, 2019 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwaterfall/9c5a88871d53f94f7f38b61a35ffaed0 to your computer and use it in GitHub Desktop.
Save mwaterfall/9c5a88871d53f94f7f38b61a35ffaed0 to your computer and use it in GitHub Desktop.
public protocol Changeable {}
extension Changeable {
/// Calls the `changes` closure passing the receiver value as an `inout` parameter. The final value of the argument
/// after the `changes` closure returns is then returned from this method. Benefits to using this function come
/// when used against value types.
///
/// Example:
///
/// extension UIEdgeInsets: Changeable {}
/// let justBottomInsets = UIEdgeInsets.zero.applying({ $0.bottom = 8 })
public func applying(_ changes: (inout Self) -> Void) -> Self {
var newValue = self
changes(&newValue)
return newValue
}
/// Mutates the receiver in-place by calling the `changes` closure and passing the receiver value as an `inout`
/// parameter. The final value of the argument after the `changes` closure returns will replace the receiver.
/// Benefits to using this function come when used against value types.
///
/// Example:
///
/// extension UIEdgeInsets: Changeable {}
/// var insets = UIEdgeInsets.zero
/// insets.apply({ $0.bottom = 8 })
public mutating func apply(_ changes: (inout Self) -> Void) {
let newValue = applying(changes)
self = newValue
}
}
extension MutableCollection where Element: Changeable {
/// Returns a collection of type `Self` with each element having `elementChanges` applied to it.
public func applyingToElements(_ elementChanges: (inout Element) -> Void) -> Self {
var newValue = self
for index in newValue.indices {
newValue[index].apply(elementChanges)
}
return newValue
}
/// Mutates the collection in-place with each element having `elementChanges` applied to it.
public mutating func applyToElements(_ elementChanges: (inout Element) -> Void) {
let newValue = applyingToElements(elementChanges)
self = newValue
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment