Skip to content

Swift Optional extension for convenient "optional chaining" calls

License

Notifications You must be signed in to change notification settings

negusoft/IfLetSwift

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Swift Optional extension to simplify conditional expresions in some cases.

Let's say we have the following code:

let optionalInt: Int? = ???
let description: String
if let amount = optionalInt {
    description = "\(amount) items"
} else {
    description = "no items"
}
print(description)

We can write the same code using IfLetSwift:

let description = optionalInt.ifLet { "\($0) items" } ?? "no items"
print(description)

So it provides a consise and readable expression.

Setup

CocoaPods

Make sure that you are using the latest CocoaPods version.

Add the following line to your podfile:

pod 'IfLetSwift'

Don't forget to update your pods and open the generated xcworkspace file:

$ pod install

You will also need to import the module in order to use the extension methods:

import IfLetSwift

Other

The library is actually a single file so you might simply copy Optional+IfLetSwift.swift to your project.

Usage

The library provides two extension methods that can be called on optional values.

  • ifLet: Receives a closure that will be called only if the optional has a value, the closure is passed the actual value. Returns the value returned by the closure or nil.
  • elseDo: Receives a closure with no arguments that is called only if the optional is nil. It is usually chained after ifLet

Please have a look at IfLetSwift.playground for samples on how to use these methods.

License

IfLetSwift is released under the MIT license. See LICENSE for details.

About

Swift Optional extension for convenient "optional chaining" calls

Resources

License

Stars

Watchers

Forks

Packages

No packages published