Created
January 28, 2019 12:25
-
-
Save mwaterfall/9c5a88871d53f94f7f38b61a35ffaed0 to your computer and use it in GitHub Desktop.
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
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