Last active
February 20, 2023 18:34
-
-
Save claybridges/753c28b90e9a6c3cc55526617d9c53f2 to your computer and use it in GitHub Desktop.
Swift with() and withLet() functions
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
/** | |
Groups operations on an item, using shorthand to reduce repetition. | |
Using this function, repetitive code like | |
``` | |
let myWellDescribedLabel = UILabel() | |
myWellDescribedLabel.attributedText = attributedStringTitle | |
myWellDescribedLabel.isAccessibilityElement = true | |
myWellDescribedLabel.numberOfLines = 1 | |
``` | |
can be replaced with | |
``` | |
let myWellDescribedLabel = with(UILabel()) { | |
$0.attributedText = attributedStringTitle | |
$0.isAccessibilityElement = true | |
$0.numberOfLines = 1 | |
} | |
``` | |
- Parameters: | |
- item: item to operate on, either a reference or value type | |
- closure: closure operating on that item | |
- Returns: item after applying closure | |
*/ | |
@discardableResult | |
public func with<T>(_ item: T, _ closure: (inout T) -> Void) -> T { | |
var mutableItem = item | |
closure(&mutableItem) | |
return mutableItem | |
} | |
/** | |
Groups operations on an *_optional_* item, using shorthand to reduce repetition. | |
This function is the optional-handling version of `with()`. Much like an if-let, the closure | |
is run only for non-nil items, and in the scope of the closure, the item is not optional | |
(e.g. referenced as `$0` and not `$0?`). | |
- Parameters: | |
- item: optional item to operate on, either a reference or value type | |
- closure: closure operating on that item | |
- Returns: item after applying closure | |
*/ | |
@discardableResult | |
public func withLet<T>(_ item: Optional<T>, _ closure: (inout T) -> Void) -> Optional<T> { | |
guard let item = item else { return nil } | |
return with(item, closure) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment