Rewrite the if let function in Swift

Tram Ho

Terms:

Closure : A closed function block that can be transmitted.
Generics : Reusable functions and types can work with any type (or subset of a certain type).
Optional : Swift introduces options for dealing with no value, simply by declaring if it’s valid or not.
Optional Binding : Use if let to safely unlock the optional.
String : A set of characters, often considered a word or sentence.

Optional Binding: If let in Swift

Optional Binding means that if an optional variable can be obtained by using if let to convert an optional variable into a non-optional variable with the same value. For example:

If let settings

We can install an if let code (Optional Binding) version as a function function.
Standard installation of optionals:
First, we need to understand how optional works in their default configuration.
An optional String can be resolved into .some or .none , as illustrated by the following code:

If let setting for String type: We can do if let using closures so if String is not optional , we can run elseFunc , if nil then run thenFunc :

Installing generics if let We can use the standard if let optional binding for any optional type. Obviously we want to install generic if let to work for any particular type.

Conclude:

Writing the Optional Binding version in Swift isn’t too complicated and lets us understand more about what’s going on in Swift.

Reference: https://medium.com/swlh/re-implement-if-let-in-swift-d88a4b79de83

Share the news now

Source : Viblo