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
,run
Reture Value
The scope functions differ by the result they return:
apply
,also
return the context object.let
,with
, andrun
return the closure result.The return value of
also
andapply
is 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
apply
for code blocks that don’t return a value and mainly operate on the members of the receiver object.also
Use
also
for additional actions that don’t alter the object, such as logging or printing debug information.let
let
can be used to invoke one or more functions on result of call chains.let
is 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.
with
can be read as “with this object, do the following.”run
Use
run
as a non-extension function. Non-extensionrun
lets 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.