let is often used for executing a code block only with non-nil values.
var org: Organization?
org = Organization(name: "podo", member: Member(name: "jayce", role: .member))
org?.member?.let {
$0.role = .owner // $0 is not nil inside '?.let {}'
}
with
A non-extension function: the context object is passed as an argument, and return value is the closure result.
with can be read as “with this object, do the following.”
let description = with(org) {
"Orgnaization name is \($0.name), "
.appending("member name is \($0.member.name)")
}
print(description)
run
Use run as a non-extension function.
Non-extension run lets you execute a block of several statements where an expression is required.
let hexNumberRegex = run { () -> Regex in
let digits = "0-9"
let hexDigits = "A-Fa-f"
let sign = "+-"
return Regex("[\(sign)]?[\(digits)\(hexDigits)]+")
}
Scope
Scoping Functions of Swift Style for Readable Code
🌷 Usage
apply,also,let,with,runReture Value
The scope functions differ by the result they return:
apply,alsoreturn the context object.let,with, andrunreturn the closure result.The return value of
alsoandapplyis the context object itself. so they can be included into call chains as side steps.They also can be used in return statements of functions returning the context object.
apply
Use
applyfor code blocks that don’t return a value and mainly operate on the members of the receiver object.also
Use
alsofor additional actions that don’t alter the object, such as logging or printing debug information.let
letcan be used to invoke one or more functions on result of call chains.letis often used for executing a code block only with non-nil values.with
A non-extension function: the context object is passed as an argument, and return value is the closure result.
withcan be read as “with this object, do the following.”run
Use
runas a non-extension function. Non-extensionrunlets you execute a block of several statements where an expression is required.⚙️ Installation
Using Swift Package Manager
Using CocoaPods
👮 License
Scope is available under the MIT license. See the LICENSE for details.