Movatterモバイル変換


[0]ホーム

URL:


Packt
Search iconClose icon
Search icon CANCEL
Subscription
0
Cart icon
Your Cart(0 item)
Close icon
You have no products in your basket yet
Save more on your purchases!discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Profile icon
Account
Close icon

Change country

Modal Close icon
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timerSALE ENDS IN
0Days
:
00Hours
:
00Minutes
:
00Seconds
Home> Programming> Object Oriented Programming> Swift 3 Object-Oriented Programming
Swift 3 Object-Oriented Programming
Swift 3 Object-Oriented Programming

Swift 3 Object-Oriented Programming: Implement object-oriented programming paradigms with Swift 3.0 and mix them with modern functional programming techniques to build powerful real-world applications , Second Edition

Arrow left icon
Profile Icon Gaston C. Hillar
Arrow right icon
Mex$180Mex$721.99
Full star iconEmpty star iconEmpty star iconEmpty star iconEmpty star icon1(1 Ratings)
eBookFeb 2017370 pages2nd Edition
eBook
Mex$180 Mex$721.99
Paperback
Mex$902.99
Subscription
Free Trial
Arrow left icon
Profile Icon Gaston C. Hillar
Arrow right icon
Mex$180Mex$721.99
Full star iconEmpty star iconEmpty star iconEmpty star iconEmpty star icon1(1 Ratings)
eBookFeb 2017370 pages2nd Edition
eBook
Mex$180 Mex$721.99
Paperback
Mex$902.99
Subscription
Free Trial
eBook
Mex$180 Mex$721.99
Paperback
Mex$902.99
Subscription
Free Trial

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Table of content iconView table of contentsPreview book icon Preview Book

Swift 3 Object-Oriented Programming

Chapter 1. Objects from the Real World to the Playground

Whenever you have to solve a problem in the real world, you use elements and interact with them. For example, when you are thirsty, you take a glass, you fill it up with water, soda, or your favorite juice, and then you drink. Similarly, you can easily recognize elements, known as objects, from real-world actions and then translate them into object-oriented code. In this chapter, we will start learning the principles of object-oriented programming to use them in Swift 3 to develop apps and applications.

Installing the required software on Mac OS

In this book, you will learn to take advantage of all the object-oriented features included in Swift programming language version 3. Some of the examples might be compatible with previous Swift versions, such as 2.3, 2.2, 2.1, and 2.0, but it is essential to use Swift 3.0 or later because this version is not backward compatible. We won't write code that is backwards compatible with previous Swift versions because our main goal is to work with Swift 3.0 or later and to use its syntax.

We will useXcode as ourIntegrated Development Environment(IDE). All the examples work with Xcode version 8 or higher. The latest versions of the IDE include Swift 3 as one of the supported programming languages to build iOS apps, watchOS apps, tvOS apps, and Mac OS applications. It is important to note that Xcode only runs on Mac OS, and all the instructions provided in this chapter consider that we are running this operating system on a Mac computer. However, after Apple launched Swift 2.2, it made the language open source and added a port to Linux, specifically to Ubuntu. Swift 3 is also available on Ubuntu. Thus, we can apply everything we learn about object-oriented programming with Swift when targeting other platforms to which the language is ported.

Tip

In case you want to work with the Swift open source release on Mac OS, you can download the latest release in theDownloads section athttp://swift.org. You can run all the code examples included in this book in theSwift Read Evaluate Print Loop command-line environment instead of working withXcode Playground. The Swift Read Evaluate Print Loop command-line environment is also known as Swift REPL.

It is also possible to use the Swift Playgrounds app on iOS 10.0 or later in the iPad models that are compatible with this app. You can work with this app to run the examples. However, our main IDE will be Xcode.

The following is the URL for the Swift Playgrounds app:https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=908519492

In order to install Xcode, you just need to launch the Mac App Store, enterXcode in the search box, click on the Xcode application icon shown in the results, and make sure that it is the application developed by Apple and not an Xcode helper application. The following screenshot shows the details of the Xcode application in the Mac App Store:

Installing the required software on Mac OS

Then, click onGet and wait until the Mac App Store downloads Xcode. Note that it is necessary to download a few GBs and therefore it may take some time to finish the download process. Once the download is finished, click onInstall and follow the necessary steps to complete the application's installation process. Finally, you will be able to launch the Xcode application as you would execute any other application in your Mac OS operating system. It is also possible to download and install Xcode fromhttp://developer.apple.com/xcode/.

Apple usually launches Xcode beta versions before releasing the final stable versions. It is highly recommended to avoid working with beta versions to test the examples included in this book because beta versions are unstable and some examples might crash or generate unexpected outputs. The Mac App Store only offers the latest stable version of Xcode, and therefore, there is no risk of installing a beta version by mistake when following the previously explained steps.

In case we have any Xcode beta version installed on the same computer in which we will run the book samples, we have to make sure that the configuration for the stable Xcode version uses the appropriate command-line tools. We won't work with the command-line tools, but we will take advantage of Playground, and this feature uses the command-line tools under the hood.

Launch Xcode, navigate toXcode |Preferences..., and click onLocations. Make sure that theCommand Line Tools drop-down menu displays the stable Xcode version that you installed as the selected option. The following screenshot showsXcode 8.0 (8A218a) as the selected version forCommand Line Tools. However, you will definitely see a higher version number because Xcode is updated frequently:

Installing the required software on Mac OS

Tip

We don't need an iOS Developer Program membership to run the examples included in this book. However, in case we want to distribute the apps or applications coded in Swift to any App Store or activate certain capabilities in Xcode, we will require an active membership.

You don't need any previous experience with the Swift programming language to work with the examples in this book and learn how to model and create object-oriented code with Swift 3. If you have some experience with Objective-C, Java, C#, Python, Ruby, or JavaScript, you will be able to easily learn Swift's syntax and understand the examples. Swift borrows many features from these and other modern programming languages, and therefore, any knowledge of these languages will be extremely useful.

Installing the required software on Ubuntu Linux

In case we want to work with Swift 3 in Ubuntu Linux, we won't be able to run the examples that interact with any iOS API. However, we will be able to run a big percentage of the sample code included in this book, and we will be able to learn the most important object-oriented principles.

We can download the latest release for our Ubuntu version in theDOWNLOAD section athttp://swift.org. This page includes all the instructions to install the required dependencies (clang andlibicu-dev) and to execute the Swift REPL command-line environment.

Once we have completed the installation, we can execute theswift command to run the REPL in a Terminal. After we see a welcome message, we can enter Swift code and the REPL will display the results of executing each code block. We can also take advantage of a set of LLDB debugging commands. We just need to enter:help to list all the available debugger commands.

The following screenshot shows the Terminal application in Ubuntu running theswift command and displaying the results after entering two lines of Swift code:

Installing the required software on Ubuntu Linux

Working with Swift 3 on the web

In case we want to work with Swift 3 in Windows or in any other platform, we can work with a web-based Swift sandbox developed by IBM. We just need to open the following web page in a web browser:https://swiftlang.ng.bluemix.net/#/repl.

The IBM Swift Sandbox mimics the Playground with a text-based UI and it allows you to enter the code on the left-hand side and watch the results of the execution on the right-hand side. The sandbox is simple and not as powerful as the Xcode Playground. As it happens with Swift in Ubuntu Linux, we won't be able to run the examples that interact with any iOS API. However, we will be able to run a big percentage of the sample code included in this book, and we will be able to learn the most important object-oriented principles with any compatible web browser.

The following screenshot shows IBM Swift Sandbox displaying the results of executing two lines of Swift code in Chrome under Windows 10. We just need to enter the Swift code on the left-hand side and click on the Execute button (play icon) to see the results of compiling and executing the code on the right-hand side:

Working with Swift 3 on the web

Capturing objects from the real world

Now, let's forget about Xcode and Swift for a while. Imagine that we have to develop a new universal iOS app that targets the iPad, iPhone, and iPod touch devices. We will have differentUser Interfaces(UI) andUser Experiences(UX) because these devices have diverse screen sizes and resolutions. However, no matter the device in which the app runs, it will have the same goal.

Imagine that Vanessa is a very popular YouTuber, painter, and craftswoman who usually uploads videos on a YouTube channel. She has more than a million followers, and one of her latest videos had a huge impact on social networking sites. In this video, she sketched basic shapes and then painted them with acrylic paint to build patterns. She worked with very attractive colors, and many famous Hollywood actresses uploaded pictures on Instagram sharing their creations with the technique demonstrated by Vanessa and with the revolutionary special colors developed by a specific acrylic paint manufacturer.

Obviously, the acrylic paint manufacturer wants to take full advantage of this situation, so he specifies the requirements for an app. The app must provide a set of predefined 2D shapes that the users can drag and drop in a document to build a pattern so that they can change both the 2D position and size. It is important to note that the shapes cannot intersect, and users cannot change the line widths because these are the basic requirements of the technique introduced by Vanessa. A user can select the desired line and fill colors for each shape. At any time, the user can tap a button, and the app must display a list of the acrylic paint tubes, bottles, or jars that the user must buy to paint the drawn pattern. Finally, the user can easily place an online order to request the suggested acrylic paint tubes, bottles, or jars. The app also generates a tutorial to explain to the user how to generate each of the final colors for the lines and fills by thinning the appropriate amount of acrylic paint with water, based on the colors that the user has specified.

The following figure shows an example of a pattern. Note that it is extremely simple to describe the objects that compose the pattern: four 2D shapes-specifically, two rectangles and two circles. If we measure the shapes, we would easily realize that they aren't two squares and two ellipses; they are two rectangles and two circles:

Capturing objects from the real world

We can easily recognize the objects; we understand that the pattern is composed of many 2D geometric shapes. Now, let's focus on the core requirement for the app, which is calculating the required amounts of acrylic paint. We have to take into account the following data for each shape included in the pattern in order to calculate the amount of acrylic paint:

  • The perimeter
  • The area
  • The line color
  • The fill color

The app allows users to use a specific color for the line that draws the borders of each shape. Thus, we have to calculate the perimeter in order to use it as one of the values that will allow us to estimate the amount of acrylic paint that the user must buy to paint each shape's border. Then, we have to calculate the area to use it as one of the values that will allow us to estimate the amount of acrylic paint that the user must buy to fill each shape's area.

We have to start working on the backend code that calculates areas and perimeters. The app will follow Vanessa's guidelines to create the patterns, and it will only support the following six shapes:

  • Squares
  • Equilateral triangles
  • Rectangles
  • Circles
  • Ellipses
  • Regular hexagons

We can start writing Swift code-specifically, six functions that calculate the areas of the previously enumerated shapes and another six to calculate their perimeters. Note that we are talking about functions, and we stopped thinking about objects; therefore, we will face some problems with this path, which we will solve with an object-oriented approach from scratch.

For example, if we start thinking about functions to solve the problem, one possible solution is to code the following twelve functions to do the job:

  • calculatedSquareArea
  • calculatedEquilateralTriangleArea
  • calculatedRectangleArea
  • calculatedCircleArea
  • calculatedEllipseArea
  • calculatedRegularHexagonArea
  • calculatedSquarePerimeter
  • calculatedEquilateralTrianglePerimeter
  • calculatedRectanglePerimeter
  • calculatedCirclePerimeter
  • calculatedEllipsePerimeter
  • calculatedRegularHexagonPerimeter

Each of the previously enumerated functions has to receive the necessary parameters of each shape and return either its calculated area or perimeter. These functions do not have side effects, that is, they do not make changes to the arguments they receive and they just return the results of the calculated perimeters. Therefore, we usecalculated instead ofcalculate as the first word for their names. This way, it will be easier for us to generate the object-oriented version as we will continue to follow the API design guidelines that Apple has provided for Swift 3.

Now, let's forget about functions for a bit. Let's recognize the real-world objects from the application's requirements that we were assigned. We have to calculate the areas and perimeters of six elements, which are six nouns in the requirements that represent real-life objects-specifically 2D shapes. Our list of real-world objects is exactly the same that Vanessa's specification uses to determine the shapes allowed to be used to create patterns. Take a look at the list:

  • Squares
  • Equilateral triangles
  • Rectangles
  • Circles
  • Ellipses
  • Regular hexagons

After recognizing the real-life objects, we can start designing our application by following an object-oriented paradigm. Instead of creating a set of functions that perform the required tasks, we can create software objects that represent the state and behavior of a square, equilateral triangle, rectangle, circle, ellipse, and regular hexagon. This way, the different objects mimic the real-world 2D shapes. We can work with the objects to specify the different attributes required to calculate the area and perimeter. Then, we can extend these objects to include the additional data required to calculate other required values, such as the quantity of acrylic paint required to paint the borders.

Now, let's move to the real world and think about each of the previously enumerated six shapes. Imagine that we have to draw each of the shapes on paper and calculate their areas and perimeters. After we draw each shape, which values will we use to calculate their areas and perimeters? Which formulae will we use?

Tip

We started working on an object-oriented design before we started coding, and therefore, we will work as if we didn't know many concepts of geometry. For example, we can easily generalize the formulae that we use to calculate the perimeters and areas of regular polygons. However, we will analyze the requirements in most cases; we still aren't experts on the subject, and we need to dive deeper into the subject before we can group classes and generalize their behavior.

The following figure shows a drawn square and the formulae that we will use to calculate the perimeter and area. We just need the length of a side, usually identified asa:

Capturing objects from the real world

The following figure shows a drawn equilateral triangle and the formulae that we will use to calculate the perimeter and area. This type of triangle has equal sides, and the three internal angles are equal to 60 degrees. We just need the length of each side, usually identified asa:

Capturing objects from the real world

The following figure shows a drawn rectangle and the formulae that we will use to calculate the perimeter and area. We need the width and height values:

Capturing objects from the real world

The following figure shows a drawn circle and the formulae that we will use to calculate the perimeter and area. We just need the radius, usually identified asr:

Capturing objects from the real world

The following figure shows a drawn ellipse and the formulae that we will use to calculate the perimeter and area. We need the semimajor axis (usually labeled asa) and semiminor axis (usually labeled asb) values:

Capturing objects from the real world

The following figure shows a drawn regular hexagon and the formulae that we will use to calculate the perimeter and area. We just need the length of each side, usually labeled asa:

Capturing objects from the real world

The following table summarizes the data required for each shape:

Shape

Required data

Square

The length of a side

Equilateral triangle

The length of a side

Rectangle

The width and height

Circle

The radius

Ellipse

The semimajor and semiminor axes

Regular hexagon

The length of a side

Each object that represents a specific shape encapsulates the required data that we identified. For example, an object that represents an ellipse will encapsulate the ellipse's semimajor and semiminor axes.

Tip

Data encapsulation is one of the major pillars of object-oriented programming.

Generating classes to create objects

Imagine that you want to draw and calculate the areas of six different ellipses. You will end up with six ellipses drawn, their different semimajor axis and semiminor axis values, and their calculated areas. It would be great to have a blueprint to simplify the process of drawing each ellipse with their different semimajor axis and semiminor axis values.

In object-oriented programming, a class is a template definition or blueprint from which objects are created. Classes are models that define the state and behavior of an object. After declaring a class that defines the state and behavior of an ellipse, we can use it to generate objects that represent the state and behavior of each real-world ellipse:

Tip

Objects are also known as instances. For example, we can say eachcircle object is an instance of theCircle class.

The following figure shows two circle instances drawn with their radius values specified:Circle #1 andCircle #2. We can use aCircle class as a blueprint to generate the two differentCircle instances. Note thatCircle #1 has a radius value of175, andCircle #2 has a radius value of350. Each instance has a different radius value:

Generating classes to create objects

The following figure shows three ellipse instances drawn with their semimajor axis and semiminor axis values specified:Ellipse #1,Ellipse #2, andEllipse #3. In this case, we can use anEllipse class as a blueprint to generate the three different ellipse instances. It is very important to understand the difference between a class and the objects or instances generated through its usage. The object-oriented programming features supported in Swift allow us to discover which blueprint we used to generate a specific object. We will use these features in many examples in the upcoming chapters. Thus, we can know that each object is an instance of theEllipse class. Each ellipse has its own specific values for the semimajor and semiminor axes:

Generating classes to create objects

We recognized six completely different real-world objects from the application's requirements, and therefore, we can generate the following six classes to create the necessary objects:

  • Square
  • EquilateralTriangle
  • Rectangle
  • Circle
  • Ellipse
  • RegularHexagon

Note the usage of Pascal case for class names; this means that the first letter of each word that composes the name is capitalized, while the other letters are in lowercase. This is a coding convention in Swift. For example, we use theRegularHexagon name for the class that will generate regular hexagons. Pascal case is also known as UpperCamelCase or Upper Camel Case.

Recognizing variables and constants to create properties

We know the information required for each of the shapes to achieve our goals. Now, we have to design the classes to include the necessary properties that provide the required data to each instance. We have to make sure that each class has the necessary variables that encapsulate all the data required by the objects to perform all the tasks based on our application domain.

Let's start with theRegularHexagon class. It is necessary to know the length of a side for each instance of this class, that is, for each regular hexagon object. Thus, we need an encapsulated variable that allows each instance of theRegularHexagon class to specify the value for the length of a side.

Tip

The variables defined in a class to encapsulate the data for each instance of the class in Swift are known asproperties. Each instance has its own independent value for the properties defined in the class. The properties allow us to define the characteristics for an instance of the class. In other programming languages, the variables defined in a class are known as eitherattributes orfields.

TheRegularHexagon class defines a floating point property namedlengthOfSide, whose initial value is equal to0 for any new instance of the class. After we create an instance of theRegularHexagon class, it is possible to change the value of thelengthOfSide attribute.

Note the usage of Camel case, which is using a lowercase first letter, for class property names. The first letter is lowercase, and then, the first letter for each word that composes the name is capitalized, while the other letters are in lowercase. It is a coding convention in Swift for both variables and properties. For example, we use thelengthOfSide name for the property that stores the value of the length of a side.

Imagine that we create two instances of theRegularHexagon class. One of the instances is namedregularHexagon1 and the other,regularHexagon2. The instance names allow us to access the encapsulated data for each object, and therefore, we can use them to change the values of the exposed properties.

Swift uses a dot (.) to allow us to access the properties of instances. So,regularHexagon1.lengthOfSide provides access to the length of side of theRegularHexagon instance namedregularHexagon1, andregularHexagon2.lengthOfSide does the same for theRegularHexagon instance namedregularHexagon2.

Tip

Note that the naming convention makes it easy for us to differentiate an instance name, that is, a variable from a class name. Whenever we see the first letter in uppercase or capitalized, it means that we are talking about a class.

We can assign20 toregularHexagon1.lengthOfSide and50 toregularHexagon2.lengthOfSide. This way, eachRegularHexagon instance will have a different value for thelengthOfSide attribute.

Now, let's move to theEllipse class. We can define two floating point attributes for this class:semiMajorAxis andsemiMinorAxis. Their initial values will also be0. Then, we can create three instances of theEllipse class namedellipse1,ellipse2, andellipse3.

We can assign the values summarized in the following table to the three instances of theEllipse class:

Instance name

semiMinorAxisvalue

semiMajorAxisvalue

ellipse1

210

400

ellipse2

180

300

ellipse3

180

356

This way,ellipse1.semiMinorAxis will be equal to210, whileellipse3.semiMinorAxis will be equal to180. Theellipse1 instance represents an ellipse withsemiMinorAxis of210 andsemiMajorAxis of400.

The following table summarizes the floating point properties defined for each of the six classes that we need for our application:

Class name

Properties list

Square

lengthOfSide

EquilateralTriangle

lengthOfSide

Rectangle

width andheight

Circle

radius

Ellipse

semiMinorAxis andsemiMajorAxis

RegularHexagon

lengthOfSide

Tip

The properties are members of their respective classes. However, properties aren't the only members that classes can have.

Note that three of these classes have the same property:lengthOfSide-specifically, theSquare,EquilateralTriangle, andRegularHexagon classes. We will dive deep into what these three classes have in common later and take advantage of object-oriented features to reuse code and simplify our application's maintenance. However, we are just starting our journey, and we will make improvements as we cover additional object-oriented features included in Swift.

The following figure shows aUnified Modeling Language(UML) class diagram with the six classes and their properties. This diagram is very easy to understand. The class name appears on the top of the rectangle that identifies each class. A rectangle below the same shape that holds the class name displays all the property names exposed by the class with a plus sign (+) as a prefix. This prefix indicates that what follows it is an attribute name in UML and a property name in Swift:

Recognizing variables and constants to create properties

Recognizing actions to create methods

So far, we have designed six classes and identified the necessary properties for each of them. Now, it is time to add the necessary pieces of code that work with the previously defined properties to perform all the tasks. We have to make sure that each class has the necessary encapsulated functions that process the property values specified in the objects to perform all the tasks.

Let's forget a bit about the similarities between the different classes. We will work with them individually as if we didn't have the necessary knowledge of geometric formulae. We will start with theSquare class. We need pieces of code that allow each instance of this class to use the value of thelengthOfSide property to calculate the area and perimeter.

Tip

The functions defined in a class to encapsulate the behavior of each instance of the class are known asmethods. Each instance can access the set of methods exposed by the class. The code specified in a method can work with the properties specified in the class. When we execute a method, it will use the properties of the specific instance. Whenever we define methods, we must make sure that we define them in a logical place, that is, in the place where the required data is kept.

When a method doesn't require parameters, we can say that it is a parameterless method. In this case, all the methods we will initially define for the classes will be parameterless methods that just work with the values of the previously defined properties and use the formulae shown in the figures. Thus, we will be able to call them without arguments. We will start creating methods, but we will be able to explore additional options based on specific Swift features later.

TheSquare class defines the following two parameterless methods. We will declare the code for both methods within the definition of theSquare class so that they can access thelengthofSide property value:

  • calculatedArea: This method returns a floating point value with the calculated area for the square. It returns the square of thelengthOfSide attribute value (lengthOfSide2 orlengthOfSide ^ 2).
  • calculatedPerimeter: This method returns a floating point value with the calculated perimeter for the square. It returns thelengthOfSide attribute value multiplied by 4 (4 * lengthOfSide).

Note the usage of Camel case, that is, using a lowercase first letter, for method names. The first letter is in lowercase, and then, the first letter for each word that composes the name is capitalized, while the other letters are in lowercase. As it happened with property names, it is a coding convention in Swift for methods.

These methods do not have side effects, that is, they do not make changes to the related instance. The methods just return the calculated values. Their operation is naturally described by thecalculate verb. We usecalculated instead ofcalculate as the first word for their names because the verb's imperative must be used for mutating methods. In this case, the methods are nonmutating, and we follow the API design guidelines that Apple provided for Swift 3.

Swift uses a dot (.) to allow us to execute the methods of the instances. Imagine that we have two instances of theSquare class:square1 with thelengthOfSide property equal to20 andsquare2 with thelengthOfSide property equal to40. If we callsquare1.calculatedArea, it will return the result of202, which is 400. If we callsquare2.calculatedArea, it will return the result of402, which is 1600. Each instance has a diverse value for thelengthOfSide attribute, and therefore, the results of executing thecalcualteArea method are different.

If we callsquare1.calculatedPerimeter, it will return the result of4 * 20, which is 80. On the other hand, if we callsquare2.calculatePerimeter, it will return the result of4 * 40, which is 160.

Now, let's move to theEquilateralTriangle class. We need exactly two methods with the same names specified for theSquare class:calculatedArea andcalculatedPerimeter. In addition, the methods return the same type and don't need parameters, so we can declare both of them as parameterless methods, as we did in theSquare class. However, these methods have to calculate the results in a different way, that is, they have to use the appropriate formulae for an equilateral triangle. The other classes also need the same two methods. However, each of them will use the appropriate formulae for the related shape.

We have a specific problem with thecalculatedPerimeter method that theEllipse class generates. Perimeters are complex to calculate for ellipses, so there are many formulae that provide approximations. An exact formula requires an infinite series of calculations. We can use an initial formula that isn't very accurate, which we will have to improve later. The initial formula will allow us to return a floating point value with the calculated approximation of the perimeter for the ellipse.

The following figure shows an updated version of the UML diagram with the six classes, their attributes, and their methods:

Recognizing actions to create methods

Organizing classes with UML diagrams

So far, our object-oriented solution includes six classes with their properties and methods. However, if we take another look at these six classes, we will notice that all of them have the same two methods:calculatedArea andcalculatedPerimeter. The code for the methods in each class is different because each shape uses a special formula to calculate either the area or the perimeter. However, the declarations, contracts, or protocols for the methods are the same. Both methods have the same name, are always parameterless, and return a floating point value. Thus, all of them return the same type.

When we talked about the six classes, we said we were talking about six different geometrical shapes or simply shapes. Thus, we can generalize the required behavior or protocol for the six shapes. These shapes must define thecalculatedArea andcalculatedPerimeter methods with the previously explained declarations. We can create a protocol to make sure that the six classes provide the required behavior.

The protocol is a special class namedShape, and it generalizes the requirements for the geometrical shapes in our application. In this case, we will work with a special class, but in the future, we will use protocols for the same goal. TheShape class declares two parameterless methods that return a floating point value:calculatedArea andcalculatedPerimeter. Then, we will declare the six classes as subclasses of theShape class, which will inherit these definitions, and provide the specific code for each of these methods.

The subclasses ofShape (Square,EquilateralTriangle,Rectangle,Circle,Ellipse, andRegularHexagon) implement the methods because they provide code while maintaining the same method declarations specified in theShape superclass.Abstraction andhierarchy are two major pillars of object-oriented programming.

Object-oriented programming allows us to discover whether an object is an instance of a specific superclass. After we change the organization of the six classes and after they become subclasses ofShape, any instance ofSquare,EquilateralTriangle,Rectangle,Circle,Ellipse, orRegularHexagon is also aShape class. In fact, it isn't difficult to explain the abstraction because we speak the truth about the object-oriented model when we say that it represents the real world. It makes sense to say that a regular hexagon is indeed a shape and therefore an instance ofRegularHexagon is aShape class. An instance ofRegularHexagon is both aShape (the superclass ofRegularHexagon) class and aRegularHexagon (the class that we used to create the object) class.

The following figure shows an updated version of the UML diagram with the superclass or base class (Shape), its six subclasses, and their attributes and methods. Note that the diagram uses a line that ends in an arrow that connects each subclass to its superclass. You can read the line that ends in an arrow as the following: the class where the line beginsis a subclass of the class that has the line ending with an arrow. For example,Square is a subclass ofShape andEquilateralTriangle is a subclass ofShape:

Organizing classes with UML diagrams

Tip

A single class can be the superclass of many subclasses.

Now, it is time to have a meeting with a domain expert, that is, someone who has an excellent knowledge of geometry. We can use the UML diagram to explain the object-oriented design for the solution. After we explain the different classes that we will use to abstract behavior, the domain expert explains to us that many of the shapes have something in common and that we can generalize behavior even further. The following three shapes are regular polygons:

  • An equilateral triangle (theEquilateralTriangle class)
  • A square (theSquare class)
  • A regular hexagon (theRegularHexagon class)

Regular polygons are polygons that are both equiangular and equilateral. All the sides that compose a regular polygon have the same length and are placed around a common center. This way, all the angles between any two sides are equal. An equilateral triangle is a regular polygon with three sides, the square has four sides, and the regular hexagon has six sides. The following picture shows the three regular polygons and the generalized formulae that we can use to calculate their areas and perimeters. The generalized formula to calculate the area requires us to calculate a cotangent, which is abbreviated ascot:

Organizing classes with UML diagrams

As the three shapes use the same formula with just a different value for the number of sides (n) parameter, we can generalize the required protocol for the three regular polygons. The protocol is a special class namedRegularPolygon that defines a newnumberOfSides property that specifies the number of sides with an integer value. TheRegularPolygon class is a subclass of the previously definedShape class. It makes sense because a regular polygon is indeed a shape. The three classes that represent regular polygons become subclasses ofRegularPolygon. However, both thecalculateArea andcalculatedPerimeter methods are coded in theRegularPolygon class using the generalized formulae. The subclasses just specify the right value for the inheritednumberOfSides property, as follows:

  • EquilateralTriangle: 3
  • Square: 4
  • RegularHexagon: 6

TheRegularPolygon class also defines thelengthOfSide property that was previously defined in the three classes that represent regular polygons. Now, the three classes become subclasses ofRegularPolygon and inherit thelengthOfSide property. The following figure shows an updated version of the UML diagram with the newRegularPolygon class and the changes in the three classes that represent regular polygons. The three classes that represent regular polygons do not declare either thecalculatedArea orcalculatedPerimeter methods because these classes inherit them from theRegularPolygon superclass and don't need to make changes to these methods that apply a general formula:

Organizing classes with UML diagrams

Our domain expert also explains to us a specific issue with ellipses. There are many formulae that provide approximations of the perimeter value for this shape. Thus, it makes sense to add additional methods that calculate the perimeter using other formulae. He suggests us to make it possible to calculate the perimeters with the following formulae:

  • The second version of the formula developed by Srinivasa Aiyangar Ramanujan
  • The formula proposed by David W. Cantrell

We will define the following two additional parameterless methods to theEllipse class. The new methods will return a floating point value and solve the specific problem of the ellipse shape:

  • CalculatedPerimeterWithRamanujanII
  • CalculatedPerimeterWithCantrell

This way, theEllipse class will implement the methods specified in theShape superclass and also add two specific methods that aren't included in any of the other subclasses ofShape. The following figure shows an updated version of the UML diagram with the new methods for theEllipse class:

Organizing classes with UML diagrams

Working with API objects in the Xcode Playground

Now, let's forget a bit about geometry, shapes, polygons, perimeters, and areas. We will interact with API objects in the Xcode Playground. You still need to learn many things before we can start creating object-oriented code. However, we will write some code in the Playground to interact with an existing API before we move forward with our journey into the object-oriented programming world.

Tip

The following example interacts with an iOS API, and therefore, you cannot run it in Ubuntu or in the web-based IBM Swift Sandbox. However, you will be able to run most of the examples that don't interact with iOS APIs in the forthcoming chapters.

Object-oriented programming is extremely useful when you have to interact with API objects. When Apple launched iOS 8, it introduced a Health app that provided iPhone users access to a dashboard of health and fitness data. TheHealthKit framework introduced in the iOS SDK 8 allows app developers to request permissions from the users themselves to read and write specific types of health and fitness data. The framework makes it possible to ask for, create, and save health and fitness data that the users will see summarized in the Health app. This app is still a very important app in iOS 10, and the Apple Watch device in its two versions can generate very useful data for this app.

When we store and query health and fitness data, we have to use the framework to work with the units in which the values are expressed, their conversions, and localizations. For example, let's imagine an app that stores body temperature data without considering the units and their conversions. A value of 39 degrees Celsius (which is equivalent to 102.2 degrees Fahrenheit) in an adult would means that the person's body temperature is higher than normal (that is, they may have a fever). However, a value of 39 degrees Fahrenheit (equivalent to 3.88 degrees Celsius) would mean that the person's body is close to its freezing point. If our app just stores values without considering the related units and user preferences, we can have huge mistakes. If the app just saves 39 degrees and thinks that the user will always display Celsius, it will still display 39 degrees to a user whose settings use Fahrenheit as the default temperature unit. Thus, the app will provide wrong information to the user.

The data in HealthKit is always represented by a double value with an associated simple or complex unit. The units are classified into types, and it is possible to check the compatibility between units before performing conversions. We can work with HealthKit quantities and units in the Swift interactive Playground and understand how simple it is to work with an object-oriented framework. It is important to note that the Playground doesn't allow us to interact with the HealthKit data store. However, we will just play with quantities and units in a few object-oriented snippets.

Start Xcode, navigate toFile |New |Playground..., enter a name forPlayground, selectiOS as the desired platform, click onNext, select the desired location for the Playground file, and click onCreate. Xcode will display a Playground window with a line that importsUIKit and creates astring variable. You just need to add the following line to be able to work with quantities and units from theHealthKit framework, as shown in the subsequent screenshot:

    import HealthKit

Working with API objects in the Xcode Playground

Tip

Xcode allows us to create playgrounds for any of the following platforms: iOS, Mac OS, and tvOS.

AllHealthKit types start with theHK prefix.HKUnitrepresents a particular unit that can be either simple or complex. Simple units for temperature are degrees Celsius and degrees Fahrenheit. A complex unit for mass/volume is ounces per liter (oz/L).HKUnitsupports many standardSI units (Système Internationale d'Unités in French,International System of Units in English) and non-SI units.

Add the following two lines to the Swift Playground and check the results on the right-hand side of the window; you will notice that they generate instances ofHKTemperatureUnit. Thus, you created two objects that represent temperature units, as follows. The code file for the sample is included in theswift_3_oop_chapter_01_01 folder:

    let degCUnit = HKUnit.degreeCelsius()     let degFUnit = HKUnit.degreeFahrenheit()

Tip

In Swift 2.x, in order to work with the APIs, it was necessary to repeat information many times. Swift 3 reduced the need to repeat information that was obvious, and therefore, we have to write less code to achieve the same goal compared with Swift 2.x. For example, in Swift 2.x, it was necessary to writeHKUnit.degreeCelsiusUnit() andHKUnit.degreeFahrenheitUnit(). TheHKUnit prefix makes it clear that we are talking about a unit, and therefore, Swift 3 removed theUnit word as a suffix of bothHKUnit.degreeCelsiusUnit() andHKUnit.degreeFahrenheitUnit(). As a result, we can write the previously shown code that usesHKUnit.degreeCelsius() andHKUnit.degreeFahrenheit().

However, there are other ways to create objects that represent temperature units. It is also possible to use theHKUnit initializer, which returns the appropriate unit instance from its string representation. For example, the following lines also generate instances ofHKTemperatureUnit for degrees in Celsius and Fahrenheit. The code file for the sample is included in theswift_3_oop_chapter_01_01 folder:

    let degCUnitFromStr = HKUnit(from: "degC")     let degFUnitFromStr = HKUnit(from: "degF")

Tip

In Swift 2.x, it was necessary to usefromString instead offrom to achieve the same goal shown in the previous lines. Swift 3 reduced the code that it is necessary to write to make API calls.

The following lines generate two instances ofHKEnergyUnit-one for kilocalories and the other for kilojoules. The code file for the sample is included in theswift_3_oop_chapter_01_01 folder:

    let kiloCaloriesUnit = HKUnit(from: "kcal")     let joulesUnit = HKUnit(from: "kJ")

The next two lines generate two instances ofHKMassUnit-one for kilograms and the other for pounds. The code file for the sample is included in theswift_3_oop_chapter_01_01 folder:

    let kiloGramsUnit = HKUnit.gramUnit(with:     HKMetricPrefix.kilo)     let poundsUnit = HKUnit.pound()

The next line generates an instance of _HKCompoundUnit because the string specifies a complex unit for mass/volume: ounces per liter (oz/L). The code file for the sample is included in theswift_3_oop_chapter_01_01 folder. The subsequent screenshot shows the results displayed in the Playground:

    let ouncesPerLiter = HKUnit(from: "oz/L")

Working with API objects in the Xcode Playground

HKQuantity encapsulates a quantity value (Double) and the unit of measurement (HKUnit). This class doesn't provide all the operations you might expect to work with quantities and their units of measure, but it allows you to perform some useful compatibility checks and conversions.

The following lines create twoHKQuantity instances with temperature units; we name the instancesbodyTemperature1 andbodyTemperature2. The former uses degrees Celsius (degCUnit) and the latter degrees Fahrenheit (degFUnit). Then, the code calls theis method with thecompatibleWith argument to make sure that eachHKQuantity instance can be converted to degrees Fahrenheit (degFUnit). Ifis returnstrue, it means that you can convert toHKUnit, which is specified as thecompatibleWith argument. We always have to call this method before calling thedoubleValue method. This way, we will avoid errors when the units aren't compatible.

ThedoubleValue method returns the quantity value converted to the unit specified as thefor argument. In this case, the two calls make sure that the value is expressed in degrees Fahrenheit, no matter what the temperature unit specified in eachHKQuantity instance is. The code file for the sample is included in theswift_3_oop_chapter_01_01 folder. The screenshot that follows the given code shows the results displayed in the Playground:

    let bodyTemperature1 = HKQuantity(unit: degCUnit,     doubleValue: 35.2)     let bodyTemperature2 = HKQuantity(unit: degFUnit,     doubleValue: 95)     print(bodyTemperature1.description)     print(bodyTemperature2.description)      if bodyTemperature1.is(compatibleWith: degFUnit) {       print("Temperature #1 in Fahrenheit degrees: \      (bodyTemperature1.doubleValue(for: degFUnit))")     }      if bodyTemperature2.is(compatibleWith: degFUnit) {       print("Temperature #2 in Fahrenheit degrees: \      (bodyTemperature2.doubleValue(for: degFUnit))")     }

Working with API objects in the Xcode Playground

The following line shows an example of the code that creates a newHKQuantity instance with a quantity and temperature unit converted from degrees Fahrenheit to degrees Celsius. There is no convert method that acts as a shortcut, so we have to calldoubleValue and use it in theHKQuantity initializer, as follows. The code file for the sample is included in theswift_3_oop_chapter_01_01 folder:

    let bodyTemperature2InDegC = HKQuantity(unit:       degCUnit, doubleValue:     bodyTemperature2.doubleValue(for: degCUnit))

Thecompare method returns aComparisonResult value that indicates whether the receiver is greater than, equal to, or less than the compatibleHKQuantity value specified as an argument. For example, the following lines comparebodyTemperature1 withbodyTemperature2 and print the results of the comparison. Note that it isn't necessary to convert both theHKQuantity instances to the same unit; they just need to be compatible, and the compare method will be able to perform the comparison by making the necessary conversions under the hood. In this case, one of the temperatures is in degrees Celsius and the other is in degrees Fahrenheit. The screenshot that follows the given code shows the results displayed in the Playground:

    let bodyTemperature2InDegC = HKQuantity(unit:       degCUnit, doubleValue:     bodyTemperature2.doubleValue(for: degCUnit))      let comparisonResult =     bodyTemperature1.compare(bodyTemperature2)     switch comparisonResult {       case ComparisonResult.orderedDescending:       print("Temperature #1 is greater than #2")       case ComparisonResult.orderedAscending:       print("Temperature #2 is greater than #1")       case ComparisonResult.orderedSame:       print("Temperature #1 is equal to Temperature #2")     }

Working with API objects in the Xcode Playground

Tip

In many cases, the APIs removed theNS prefix in Swift 3. In Swift 2.3, thecompare method returned anNSComparisonResult value. In Swift 3, the compare method returns aComparisonResult value. In addition, the APIs in Swift 3 use lowerCamelCase for enumeration values. Therefore, theNSComparisonResult.OrderedDescending value in Swift 2.3 isComparisonResult.orderedDescending in Swift 3.

Exercises

Now that you understand what an object is, it is time to recognize objects in different applications:

  • Exercise 1: Work with an iOS app and recognize its objects. Work with an app that has both an iPhone and iPad version. Execute the app in both versions and recognize the different objects that the developers might have used to code the app. Create a UML diagram with the classes that you would use to create the Think about the methods and properties that you would require for each class. If the app is extremely complex, just focus on a specific feature.
  • Exercise 2: Work with a Mac OS application and recognize its objects. Execute the app and work with a specific feature. Recognize the objects that interact to enable you to work with the feature. Write down the objects you recognized and their required behaviors.

Test your knowledge

  1. Objects are also known as:
    1. Classes
    2. Subclasses
    3. Instances

  2. The code specified in a method within a class:
    1. Cannot access the properties specified in the class
    2. Can access the properties specified in the class
    3. Cannot interact with other members of the class

  3. A subclass:
    1. Inherits all members from its superclass
    2. Inherits only methods from its superclass
    3. Inherits only properties from its superclass

  4. The variables defined in a class to encapsulate data for each instance of the class in Swift are known as:
    1. Subclasses
    2. Properties
    3. Methods

  5. The functions defined in a class to encapsulate behavior for each instance of the class are known as:
    1. Subclasses
    2. Properties
    3. Methods

  6. Which of the following conventions is appropriate for enumeration values in Swift 3:
    1. lowerCamelCase
    2. UpperCamelCase
    3. ALL UPPERCASE

  7. Which of the following class names follow the PascalCase convention, also known as the UpperCamelCase convention, and would be an appropriate name for a class in Swift 3:
    1. regularHexagon
    2. RegularHexagon
    3. Regularhexagon

  8. Which of the following method names would be appropriate for a non-mutating method that returns the calculated perimeter for a square in Swift 3, considering the API design guidelines:
    1. calculatedPerimeter
    2. calculatePerimeter
    3. calculateThePerimeter

  9. Which of the following method names would be appropriate for a mutating method that saves the calculated perimeter of an instance's property for a square in Swift 3, considering the API design guidelines:
    1. calculatedPerimeter
    2. calculatePerimeter
    3. calculatingPerimeter

Summary

In this chapter, you learned how to recognize real-world elements and translate them into the different components of the object-oriented paradigm supported in Swift 3: classes, protocols, properties, methods, and instances. You understood that the classes represent blueprints or templates to generate the objects, also known as instances.

We designed a few classes with properties and methods that represent blueprints for real-life objects. Then, we improved the initial design by taking advantage of the power of abstraction and specialized different classes. We generated many versions of the initial UML diagram as we added superclasses and subclasses. Finally, we wrote some code in the Swift Playground to understand how we can interact with API objects. We recognized many differences between Swift 3 and the previous versions of the programming language when interacting with APIs.

Now that you have learned some of the basics of the object-oriented paradigm, we are ready to start creating classes and instances in Swift 3, which is the topic of the next chapter.

Left arrow icon

Page1 of 13

Right arrow icon
Download code iconDownload Code

Key benefits

  • Leverage the most efficient object-oriented design patterns in your Swift applications
  • Write robust, safer, and better code using the blueprints that generate objects
  • Build a platform with object-oriented code using real-world elements and represent them in your apps

Description

Swift has quickly become one of the most-liked languages and developers’ de-facto choice when building applications that target iOS and macOS. In the new version, the Swift team wants to take its adoption to the next level by making it available for new platforms and audiences.This book introduces the object-oriented paradigm and its implementation in the Swift 3 programming language to help you understand how real-world objects can become part of fundamental reusable elements in the code. This book is developed with XCode 8.x and covers all the enhancements included in Swift 3.0. In addition, we teach you to run most of the examples with the Swift REPL available on macOS and Linux, and with a Web-based Swift sandbox developed by IBM capable of running on any web browser, including Windows and mobile devices.You will organize data in blueprints that generate instances. You’ll work with examples so you understand how to encapsulate and hide data by working with properties and access control. Then, you’ll get to grips with complex scenarios where you use instances that belong to more than one blueprint. You’ll discover the power of contract programming and parametric polymorphism. You’ll combine generic code with inheritance and multiple inheritance. Later, you’ll see how to combine functional programming with object-oriented programming and find out how to refactor your existing code for easy maintenance.

Who is this book for?

This book is for iOS and macOS developers who want to get a detailed practical understanding of object-oriented programming with the latest version of Swift: 3.0.

What you will learn

  • * Write high-quality and easy-to-maintain reusable object-oriented code to build applications for iOS, macOS, and Linux
  • * Work with encapsulation, abstraction, and polymorphism using Swift 3.0
  • * Work with classes, instances, properties, and methods in Swift 3.0
  • * Take advantage of inheritance, specialization, and the possibility to overload or override members
  • * Implement encapsulation, abstraction, and polymorphism
  • * Explore functional programming techniques mixed with object-oriented code in Swift 3.0
  • * Understand the differences between Swift 3.0, previous Swift versions, and Objective-C code

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date :Feb 27, 2017
Length:370 pages
Edition :2nd
Language :English
ISBN-13 :9781787120990
Vendor :
Apple
Category :
Languages :
Tools :

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Product Details

Publication date :Feb 27, 2017
Length:370 pages
Edition :2nd
Language :English
ISBN-13 :9781787120990
Vendor :
Apple
Category :
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99billed monthly
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconSimple pricing, no contract
$199.99billed annually
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconChoose a DRM-free eBook or Video every month to keep
Feature tick iconPLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick iconExclusive print discounts
$279.99billed in 18 months
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconChoose a DRM-free eBook or Video every month to keep
Feature tick iconPLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick iconExclusive print discounts

Frequently bought together


Mastering Swift 3
Mastering Swift 3
Read more
Oct 2016392 pages
Full star icon4.3 (8)
eBook
eBook
Mex$180Mex$803.99
Mex$1004.99
Swift 4 Programming Cookbook
Swift 4 Programming Cookbook
Read more
Sep 2017384 pages
Full star icon4.4 (5)
eBook
eBook
Mex$180Mex$803.99
Mex$1004.99
Swift 3 Object-Oriented Programming
Swift 3 Object-Oriented Programming
Read more
Feb 2017370 pages
Full star icon1 (1)
eBook
eBook
Mex$180Mex$721.99
Mex$902.99
Stars icon
TotalMex$2,912.97
Mastering Swift 3
Mex$1004.99
Swift 4 Programming Cookbook
Mex$1004.99
Swift 3 Object-Oriented Programming
Mex$902.99
TotalMex$2,912.97Stars icon
Buy 2+ to unlockMex$145 prices - master what's next.
SHOP NOW

Table of Contents

9 Chapters
1. Objects from the Real World to the PlaygroundChevron down iconChevron up icon
1. Objects from the Real World to the Playground
Installing the required software on Mac OS
Installing the required software on Ubuntu Linux
Working with Swift 3 on the web
Capturing objects from the real world
Generating classes to create objects
Recognizing variables and constants to create properties
Recognizing actions to create methods
Organizing classes with UML diagrams
Working with API objects in the Xcode Playground
Exercises
Test your knowledge
Summary
2. Structures, Classes, and InstancesChevron down iconChevron up icon
2. Structures, Classes, and Instances
Understanding structures, classes, and instances
Understanding initialization and its customization
Understanding deinitialization and its customization
Understanding automatic reference counting
Declaring classes
Customizing initialization
Customizing deinitialization
Creating the instances of classes
Exercises
Test your knowledge
Summary
3. Encapsulation of Data with PropertiesChevron down iconChevron up icon
3. Encapsulation of Data with Properties
Understanding elements that compose a class
Declaring stored properties
Generating computed properties with setters and getters
Combining setters, getters, and a related property
Understanding property observers
Transforming values with setters and getters
Creating values shared by all the instances of a class with type properties
Creating mutable classes
Building immutable classes
Exercises
Test your knowledge
Summary
4. Inheritance, Abstraction, and SpecializationChevron down iconChevron up icon
4. Inheritance, Abstraction, and Specialization
Creating class hierarchies to abstract and specialize behavior
Understanding inheritance
Declaring classes that inherit from another class
Overriding and overloading methods
Overriding properties
Controlling whether subclasses can or cannot override members
Working with typecasting and polymorphism
Taking advantage of operator overloading
Declaring compound assignment operator functions
Declaring unary operator functions
Declaring operator functions for specific subclasses
Exercises
Test your knowledge
Summary
5. Contract Programming with ProtocolsChevron down iconChevron up icon
5. Contract Programming with Protocols
Understanding how protocols work in combination with classes
Declaring protocols
Declaring classes that adopt protocols
Taking advantage of the multiple inheritance of protocols
Combining inheritance and protocols
Working with methods that receive protocols as arguments
Downcasting with protocols and classes
Treating instances of a protocol type as a different subclass
Specifying requirements for properties
Specifying requirements for methods
Combining class inheritance with protocol inheritance
Exercises
Test your knowledge
Summary
6. Maximization of Code Reuse with Generic CodeChevron down iconChevron up icon
6. Maximization of Code Reuse with Generic Code
Understanding parametric polymorphism and generic code
Declaring a protocol to be used as a constraint
Declaring a class that conforms to multiple protocols
Declaring subclasses that inherit the conformance to protocols
Declaring a class that works with a constrained generic type
Using a generic class for multiple types
Combining initializer requirements in protocols with generic types
Declaring associated types in protocols
Creating shortcuts with subscripts
Declaring a class that works with two constrained generic types
Using a generic class with two generic type parameters
Inheriting and adding associated types in protocols
Generalizing existing classes with generics
Extending base types to conform to custom protocols
Test your knowledge
Exercises
Summary
7. Object-Oriented and Functional ProgrammingChevron down iconChevron up icon
7. Object-Oriented and Functional Programming
Refactoring code to take advantage of object-oriented programming
Understanding functions as first-class citizens
Working with function types within classes
Creating a functional version of array filtering
Writing equivalent closures with simplified code
Creating a data repository with generics and protocols
Filtering arrays with complex conditions
Using map to transform values
Combining map with reduce
Chaining filter, map, and reduce
Solving algorithms with reduce
Exercises
Test your knowledge
Summary
8. Extending and Building Object-Oriented CodeChevron down iconChevron up icon
8. Extending and Building Object-Oriented Code
Putting together all the pieces of the object-oriented puzzle
Adding methods with extensions
Adding computed properties to a base type with extensions
Declaring new convenience initializers with extensions
Defining subscripts with extensions
Working with object-oriented code in iOS apps
Adding an object-oriented data repository to a project
Interacting with an object-oriented data repository through Picker View
Exercises
Test your knowledge
Summary
9. Exercise AnswersChevron down iconChevron up icon
Chapter 1, Objects from the Real World to Playground
Chapter 2, Structures, Classes, and Instances
Chapter 3, Encapsulation of Data with Properties
Chapter 4, Inheritance, Abstraction, and Specialization
Chapter 5, Contract Programming with Protocols
Chapter 6, Maximization of Code Reuse with Generic Code
Chapter 7, Object-Oriented Programming and Functional Programming
Chapter 8, Protection and Organization of Code

Recommendations for you

Left arrow icon
Debunking C++ Myths
Debunking C++ Myths
Read more
Dec 2024226 pages
Full star icon5 (1)
eBook
eBook
Mex$180Mex$656.99
Mex$820.99
Go Recipes for Developers
Go Recipes for Developers
Read more
Dec 2024350 pages
eBook
eBook
Mex$180Mex$656.99
Mex$820.99
50 Algorithms Every Programmer Should Know
50 Algorithms Every Programmer Should Know
Read more
Sep 2023538 pages
Full star icon4.5 (64)
eBook
eBook
Mex$180Mex$820.99
Mex$1025.99
Mex$1025.99
Asynchronous Programming with C++
Asynchronous Programming with C++
Read more
Nov 2024424 pages
Full star icon5 (1)
eBook
eBook
Mex$180Mex$689.99
Mex$861.99
Modern CMake for C++
Modern CMake for C++
Read more
May 2024504 pages
Full star icon4.7 (13)
eBook
eBook
Mex$180Mex$820.99
Mex$1025.99
Learn Python Programming
Learn Python Programming
Read more
Nov 2024616 pages
Full star icon3.5 (2)
eBook
eBook
Mex$180Mex$656.99
Mex$820.99
Learn to Code with Rust
Learn to Code with Rust
Read more
Sep 202557hrs 40mins
Full star icon5 (1)
Video
Video
Mex$180Mex$1538.99
Modern Python Cookbook
Modern Python Cookbook
Read more
Jul 2024818 pages
Full star icon4.9 (17)
eBook
eBook
Mex$180Mex$902.99
Mex$1128.99
Right arrow icon

Customer reviews

Rating distribution
Full star iconEmpty star iconEmpty star iconEmpty star iconEmpty star icon1
(1 Ratings)
5 star0%
4 star0%
3 star0%
2 star0%
1 star100%
frankieho120Aug 02, 2018
Full star iconEmpty star iconEmpty star iconEmpty star iconEmpty star icon1
I think it is a very poor book.
Amazon Verified reviewAmazon

People who bought this also bought

Left arrow icon
50 Algorithms Every Programmer Should Know
50 Algorithms Every Programmer Should Know
Read more
Sep 2023538 pages
Full star icon4.5 (64)
eBook
eBook
Mex$180Mex$820.99
Mex$1025.99
Mex$1025.99
Event-Driven Architecture in Golang
Event-Driven Architecture in Golang
Read more
Nov 2022384 pages
Full star icon4.9 (10)
eBook
eBook
Mex$180Mex$820.99
Mex$1025.99
Mex$922.99
The Python Workshop Second Edition
The Python Workshop Second Edition
Read more
Nov 2022600 pages
Full star icon4.6 (19)
eBook
eBook
Mex$180Mex$853.99
Mex$1066.99
Template Metaprogramming with C++
Template Metaprogramming with C++
Read more
Aug 2022480 pages
Full star icon4.6 (13)
eBook
eBook
Mex$180Mex$771.99
Mex$963.99
Domain-Driven Design with Golang
Domain-Driven Design with Golang
Read more
Dec 2022204 pages
Full star icon4.4 (18)
eBook
eBook
Mex$180Mex$738.99
Mex$922.99
Right arrow icon

About the author

Profile icon Gaston C. Hillar
Gaston C. Hillar
Gaston C. Hillar is Italian and has been working with computers since he was 8 years old. Gaston has a Bachelor's degree in computer science (graduated with honors) and an MBA. Currently, Gaston is an independent IT consultant and a freelance author who is always looking for new adventures anywhere in the world. He was a senior contributing editor at Dr. Dobb's, and has written more than a hundred articles on software development topics. He has received the prestigious Intel Black Belt Software Developer award eight times. He has written many articles about Java for Oracle Java Magazine. Gaston was also a former Microsoft MVP in technical computing. He lives with his wife, Vanesa, and his two sons, Kevin and Brandon.
Read more
See other products by Gaston C. Hillar
Getfree access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook?Chevron down iconChevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website?Chevron down iconChevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook?Chevron down iconChevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support?Chevron down iconChevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks?Chevron down iconChevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook?Chevron down iconChevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.

Create a Free Account To Continue Reading

Modal Close icon
OR
    First name is required.
    Last name is required.

The Password should contain at least :

  • 8 characters
  • 1 uppercase
  • 1 number
Notify me about special offers, personalized product recommendations, and learning tips By signing up for the free trial you will receive emails related to this service, you can unsubscribe at any time
By clicking ‘Create Account’, you are agreeing to ourPrivacy Policy andTerms & Conditions
Already have an account? SIGN IN

Sign in to activate your 7-day free access

Modal Close icon
OR
By redeeming the free trial you will receive emails related to this service, you can unsubscribe at any time.

[8]ページ先頭

©2009-2025 Movatter.jp