As we can understand by its name “Optional” that means It may or may not have some value. it is the process to call the methods and structure if it has some value it returns some value if not it return nil, it is Optional Chaining.
Optional Chaining as an Alternative to Forced Unwrapping
If you are using optional chaining then you need to specify it as in the below
1 2 3 4 5 6 7 8 9 10 11 |
class HomeViewModel: NSObject { var name:String? } class MainviewController: UIViewController { var homeViewModel: HomeViewModel! override func viewDidLoad() { super.viewDidLoad() print(homeViewModel!.name) } } |
you are using Forced Unwrapping then it must have some value else this code generate always error
Once you determine the type does contain optional values, you can add an optional name behind an exclamation point (!) To get the value. The exclamation point said, “I know that there are optional values, use it.” This is called mandatory optional parsed value (forced unwrapping).
if you want to use option chaining you need to use a question mark at the place exclamation mark like below
1 2 3 4 5 6 7 8 9 10 11 12 |
class HomeViewModel: NSObject { var name:String? } class MainviewController: UIViewController { var homeViewModel: HomeViewModel? override func viewDidLoad() { super.viewDidLoad() print(homeViewModel?.name) } } |
If the name not any value it will return nil but it doesn’t generate any error at the run time.
Accessing Properties Through Optional Chaining
You can access the properties of other classes, structures, etc by making their object. like below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class ViewController: UIViewController { var homeViewModel: HomeViewModel? override func viewDidLoad() { super.viewDidLoad() print(homeViewModel.homeModal.viewData[0].name) } } class HomeViewModel: NSObject { var homeModal: HomeModal? } struct HomeModal { var viewData = [Product]() } class Productcollection: Object { var name:String? convenience init (value: String) { self.init() self.name = value } } |
Calling Methods
You can call a method like below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class ViewController: UIViewController { var homeViewModel: HomeViewModel? override func viewDidLoad() { super.viewDidLoad() if homeViewModel.printname() != nil { }else{ } } } class HomeViewModel: NSObject { func printname(){ print("test) } } |
The whole point to get an unwrapped copy of the original object that you can use safely, even if your original object could be modified by other threads as well. So don’t discard the safely unwrapped value, use that value later on instead of doing optional chaining on the optional value.
I hope this blog helped, If you have any query please leave a comment to us and for more blogs please click here.