Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
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 Profile Icon Gaston C. Hillar
Arrow right icon
€17.99 €26.99
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1 (1 Ratings)
eBook Feb 2017 370 pages 2nd Edition
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Gaston C. Hillar Profile Icon Gaston C. Hillar
Arrow right icon
€17.99 €26.99
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1 (1 Ratings)
eBook Feb 2017 370 pages 2nd Edition
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Swift 3 Object-Oriented Programming

Understanding deinitialization and its customization


At some specific times, our app won't need to work with an instance anymore. For example, once you calculate the perimeter of a regular hexagon and display the results to the user, you don't need the specific RegularHexagon instance anymore. Some programming languages require you to be careful about leaving live instances alive, and you have to explicitly destroy them and deallocate the memory that it consumed.

Swift uses an automatic reference counting, also known as ARC, to automatically deallocate the memory used by instances that aren't being referenced anymore. When Swift detects that you aren't referencing an instance anymore, Swift executes the code specified within the instance's deinitializer before the instance is deallocated from memory. Thus, the deinitializer can still access all of the instance's resources.

Note

You can think of deinitializers as equivalents of destructors in other programming languages such as C# and Java....

Understanding automatic reference counting


Automatic reference counting is very easy to understand. Imagine that we have to distribute the items that we store in a box. After we distribute all the items, we must throw the box in a recycle bin. We cannot throw the box in the recycle bin when we still have one or more items in it. Seriously, we don't want to lose the items we have to distribute because they are very expensive.

The problem has a very easy solution; we just need to count the number of items that remain in the box. When the number of items in the box reaches zero, we can get rid of the box.

Note

One or more variables can hold a reference to a single instance of a class. Thus, it is necessary to count the number of references to an instance before Swift can get rid of an instance. When the number of references to a specific instance reaches zero, Swift can automatically and safely remove the instance from memory because nobody needs this specific instance anymore.

For example, you...

Declaring classes


The following lines declare a new minimal Circle class in Swift. The code file for the sample is included in the swift_3_oop_chapter_02_01 folder:

    class Circle { 
    } 

The class keyword, followed by the class name (Circle), composes the header of the class definition. In this case, the class doesn't have a parent class or superclass; therefore, there are neither superclasses listed after the class name nor a colon (:). A pair of curly braces ({}) encloses the class body after the class header. In the forthcoming chapters, we will declare classes that inherit from another class, and therefore, they will have a superclass. In this case, the class body is empty. The Circle class is the simplest possible class we can declare in Swift.

Note

Any new class you create that doesn't specify a superclass is considered a base class. Whenever you declare a class without a subclass, the class doesn't inherit from a universal base class, as happens in other programming languages such...

Customizing initialization


We want to initialize instances of the Circle class with the radius value. In order to do so, we can take advantage of customized initializers. Initializers aren't methods, but we will write them with syntax that is very similar to the instance methods. They will use the init keyword to differentiate from instance methods, and Swift will execute them automatically when we create an instance of a given type. Swift runs the code within the initializer before any other code within a class.

We can define an initializer that receives the radius value as an argument and use it to initialize a property with the same name. We can define as many initializers as we want to, and therefore, we can provide many different ways of initializing a class. In this case, we just need one initializer.

The following lines create a Circle class and define an initializer within the class body. The code file for the sample is included in the swift_3_oop_chapter_02_02 folder:

    class Circle...

Customizing deinitialization


We want to know when the instances of the Circle class will be removed from memory; that is, when the objects aren't referenced by any variable and automatic reference count mechanism decides that they have to be removed from memory. Deinitializers are special parameterless class methods that are automatically executed just before the runtime destroys an instance of a given type. Thus, we can use them to add any code we want to run before the instance is destroyed. We cannot call a deinitializer; they are only available for the runtime.

The deinitializer is a special method that uses the deinit keyword in its declaration. The declaration must be parameterless, and it cannot return a value.

The following lines declare a deinitializer within the body of the Circle class:

    deinit { 
      print("I'm destroying the Circle instance with a 
      radius value of \(radius).") 
    } 

The following lines show the new complete code for the Circle class. The code file...

Creating the instances of classes


The following lines create an instance of the Circle class named circle within the scope of a generatedCircleRadius function. The code within the function uses the created instance to access and return the value of its radius property. In this case, the code uses the let keyword to declare an immutable reference to the Circle instance named circle. An immutable reference is also known as a constant reference because we cannot replace the reference held by the circle constant to another instance of Circle. When we use the var keyword, we declare a reference that we can change later.

After we define the new function, we will call it. Note that the screenshot displays the results of the execution of the initializer and then the deinitializer. Swift destroys the instance after the circle constant goes out of scope because its reference count goes down from one to zero; therefore, there is no reason to keep the instance alive. Enter the following lines in the...

Exercises


Now that you understand an instance's life cycle, it is time to spend some time in the Playground, the Swift REPL, or the Swift Sandbox, creating new classes and instances:

  • Exercise 1: Create a new Employee class with a custom initializer that requires two string arguments: firstName and lastName. Use the arguments to initialize properties with the same names as the arguments. Display a message with the values for firstName and lastName when an instance of the class is created. Display a message with the values for firstName and lastName when an instance of the class is destroyed.

    • Create an instance of the Employee class and assign it to a variable. Check the messages printed in the Playground's Debug area. Assign a new instance of the Employee class to the previously defined variable. Check the messages printed in the Playground's Debug area.

  • Exercise 2: Create a function that receives two string arguments: firstName and lastName. Create an instance of the previously defined...

Test your knowledge


  1. Swift uses one of the following mechanisms to automatically deallocate the memory used by instances that aren't referenced anymore:

    1. Automatic Random Garbage Collector.

    2. Automatic Reference Counting.

    3. Automatic Instance Map Reduce.

  2. Swift executes an instance's deinitializer:

    1. Before the instance is deallocated from memory.

    2. After the instance is deallocated from memory.

    3. After the instance memory is allocated.

  3. A deinitializer:

    1. Can still access all of the instance's resources.

    2. Can only access the instance's methods but no properties.

    3. Cannot access any of the instance's resources.

  4. Swift allows us to define:

    1. Only one initializer per class.

    2. A main initializer and two optional secondary initializers.

    3. Many initializers with different arguments.

  5. Each time we create an instance:

    1. We must use argument labels.

    2. We can optionally use argument labels.

    3. We don't need to use argument labels.

  6. Which of the following lines retrieves the runtime type as a value for an instance called circle1 in Swift 3:...

Summary


In this chapter, you learned about an object's life cycle. You also learned how object initializers and deinitializers work. We declared our first class to generate a blueprint for objects. We customized object initializers and deinitializers and tested their personalized behavior in action with live examples in Swift's Playground. We understood how they work in combination with automatic reference counting. You also learned how we can run the samples in the Swift REPL and the web-based Swift Sandbox.

Now that you have learned to start creating classes and instances, you are ready to share, protect, use, and hide data with the data encapsulation features included in Swift, which is the topic of the next chapter.

Exercises

Now that you understand an instance's life cycle, it is time to spend some time in the Playground, the Swift REPL, or the Swift Sandbox, creating new classes and instances:

  • Exercise 1: Create a new Employee class with a custom initializer that requires two string arguments: firstName and lastName. Use the arguments to initialize properties with the same names as the arguments. Display a message with the values for firstName and lastName when an instance of the class is created. Display a message with the values for firstName and lastName when an instance of the class is destroyed.
    • Create an instance of the Employee class and assign it to a variable. Check the messages printed in the Playground's Debug area. Assign a new instance of the Employee class to the previously defined variable. Check the messages printed in the Playground's Debug area.

  • Exercise 2: Create a function that receives two string arguments: firstName and lastName. Create an instance of the previously...

Test your knowledge

  1. Swift uses one of the following mechanisms to automatically deallocate the memory used by instances that aren't referenced anymore:
    1. Automatic Random Garbage Collector.
    2. Automatic Reference Counting.
    3. Automatic Instance Map Reduce.

  2. Swift executes an instance's deinitializer:
    1. Before the instance is deallocated from memory.
    2. After the instance is deallocated from memory.
    3. After the instance memory is allocated.

  3. A deinitializer:
    1. Can still access all of the instance's resources.
    2. Can only access the instance's methods but no properties.
    3. Cannot access any of the instance's resources.

  4. Swift allows us to define:
    1. Only one initializer per class.
    2. A main initializer and two optional secondary initializers.
    3. Many initializers with different arguments.

  5. Each time we create an instance:
    1. We must use argument labels.
    2. We can optionally use argument labels.
    3. We don't need to use argument labels.

  6. Which of the following lines retrieves the runtime type as a value for an instance called...

Summary

In this chapter, you learned about an object's life cycle. You also learned how object initializers and deinitializers work. We declared our first class to generate a blueprint for objects. We customized object initializers and deinitializers and tested their personalized behavior in action with live examples in Swift's Playground. We understood how they work in combination with automatic reference counting. You also learned how we can run the samples in the Swift REPL and the web-based Swift Sandbox.

Now that you have learned to start creating classes and instances, you are ready to share, protect, use, and hide data with the data encapsulation features included in Swift, which is the topic of the next chapter.

Left arrow icon Right arrow icon
Download code icon Download 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 icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 106.97
Swift 3 Object-Oriented Programming
€32.99
Mastering Swift 3
€36.99
Swift 4 Programming Cookbook
€36.99
Total 106.97 Stars icon

Table of Contents

9 Chapters
1. Objects from the Real World to the Playground Chevron down icon Chevron up icon
2. Structures, Classes, and Instances Chevron down icon Chevron up icon
3. Encapsulation of Data with Properties Chevron down icon Chevron up icon
4. Inheritance, Abstraction, and Specialization Chevron down icon Chevron up icon
5. Contract Programming with Protocols Chevron down icon Chevron up icon
6. Maximization of Code Reuse with Generic Code Chevron down icon Chevron up icon
7. Object-Oriented and Functional Programming Chevron down icon Chevron up icon
8. Extending and Building Object-Oriented Code Chevron down icon Chevron up icon
9. Exercise Answers Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
(1 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 100%
frankieho120 Aug 02, 2018
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
I think it is a very poor book.
Amazon Verified review Amazon
Get free 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 icon Chevron 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 icon Chevron 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 icon Chevron 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 icon Chevron 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 icon Chevron 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 icon Chevron 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.