Chapter – 7 Optionals




 

Optionals type is used to handle if there is no value , it says there is a value and it is equal to x or there is not a value at all.
It has two value None or SomeValue(T) where T is an associated value

For Example :
for string
var someStr: String? or its is equal to var someStr: String? = nil
for Integer
var someInt: Int? or its equal to var someInt: Int? = nil

How to Use it

var someStr: String? = nil
if someStr != nil
{
print(someStr)
}
else
{
print(“someStr has nil value”)
}
Output
someStr has nil value



Forced Unwrapping

If our variable is optional for example : var someString:String?, then to get the value from optional variable we have to unwrap it.
! mark is used at the end of the variable for unwrap force fully to a variable.

 

For Example :

If we use simple optional code and assign some value in it then we first run and check its output

var someStr: String? = nil
someStr = "Hello This is 9to5iOS"
if someStr != nil
{
print(someStr)
}
else
{
print("someStr has nil value")
}
Output
Optional("Hello This is 9to5iOS")
main.swift:5:7: warning: expression implicitly coerced from 'String?' to Any
print(someStr)
^~~~~~~
main.swift:5:7: note: provide a default value to avoid this warning
print(someStr)
^~~~~~~
?? <#default value#>
main.swift:5:7: note: force-unwrap the value to avoid this warning
print(someStr)
^~~~~~~
!
main.swift:5:7: note: explicitly cast to Any with 'as Any' to silence this warning
print(someStr)
^~~~~~~
as Any

Now we force unwrap it using ! mark and check the output

var someStr: String? = nil
someStr = "Hello This is 9to5iOS"
if someStr != nil
{
print(someStr!)
}
else
{
print("someStr has nil value")
}
Output 
$swift main.swift
Hello This is 9to5iOS



Automatic Unwrapping

We can achieve the same task of force wrapping via automatic unwrapping if we use ! mark (exclamation mark) while declare our optional variables

for example 
var someStr:String!
someStr = "Hello this is 9to5iOS"
if someStr != nil
{
print(someStr)
}
else
{
print("someStr has nil value")
}
Output
$swift main.swift
Hello this is 9to5iOS



Optional Binding

Optional binding is used to check out if an optional contains a value if it contains then it is used to make that value available as temporary variable or constant
if syntax for optional binding

if let name_of_constant = some_optional
{
execute next statement
}

For Example

var someStr:String?
someStr = "Hello this is 9to5iOS"
if let someNewStr = someStr
{
print("someNewStr value = \(someNewStr)")
}
else
{
print("someNewStr contain no value")
}

Output

$swift main.swift
someNewStr value = Hello this is 9to5iOS



Add a Comment

Your email address will not be published. Required fields are marked *