Created
April 7, 2022 08:13
-
-
Save damodarnamala/cb8f73aaba8c739587025aa2eeaf3b55 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
var sides: Sides = .east | |
struct ContentView: View { | |
@State var animate = false | |
var body: some View { | |
VStack { | |
Text("Hi") | |
}.onAppear { | |
sides.apply { side in | |
side = .north | |
} | |
print(sides) | |
} | |
} | |
} | |
enum Sides: Changeable { | |
case east | |
case west | |
case north | |
case south | |
} | |
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