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:
1 2 3 4 5 6 | let optionalString: String? = "A String" if let str = optionalString { print (str) } |
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:
1 2 3 4 5 6 7 8 9 | let nilString: String? = nil switch nilString { case .some(let val): print (val) case .none: print ("this is nil") } |
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 :
1 2 3 4 5 6 7 8 9 10 11 12 13 | func iflet(_ value: String?, thenFunc: (String) -> (), elseFunc: () -> ()) { switch value { case .some(let val): thenFunc(val) default: elseFunc() } } let nilString: String? = nil iflet(nilString, thenFunc: {val in print(val)}, elseFunc: { print("Do else") } ) iflet("valueString", thenFunc: {val in print(val)}, elseFunc: { print("Do else") } ) |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | func genIfLet<T>(_ value: T?, thenFunc: (T) -> (), elseFunc: ()-> ()) { switch value { case .some(let val): thenFunc(val) default: elseFunc() } } let nilString: String? = nil genIfLet(nilString, thenFunc: {val in print(val)}, elseFunc: { print("Do else") } ) let nilInteger: Int? = 4 genIfLet(nilInteger, thenFunc: {val in print(val)}, elseFunc: { print("Do else") } ) |
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