​Swift is a powerful and intuitive development language for macOS, iOS, watchOS and tvOS....

Page 177

Swift

Program for Optional Chaining with '?' class ElectionPoll { var candidate: Pollbooth? } class Pollbooth { var name = "MP" }

let cand = ElectionPoll()

if let candname = cand.candidate?.name { println("Candidate name is \(candname)") } else { println("Candidate name cannot be retreived") } When we run the above program using playground, we get the following result: Candidate name cannot be retreived The program above declares 'election poll' as class name and contains 'candidate' as membership function. The subclass is declared as 'poll booth' and 'name' as its membership function which is initialized as 'MP'. The call to the super class is initialized by creating an instance 'cand' with optional '?'. Since the values are not declared in its base class 'nil' value is stored and printed in the console by the else handler block.

Defining Model Classes for Optional Chaining & Accessing Properties Swift language also provides the concept of optional chaining, to declare more than one subclasses as model classes. This concept will be very useful to define complex models and to access the properties, methods and subscripts sub properties. class rectangle { var print: circle? }

class circle { var area = [radius]() var cprint: Int { 165


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.