Beginning iOS 11 Programming with Swift

Posted: November 21, 2017 by Mike Hubbartt in Academia, Development, Software Reviews
Tags: , , , ,

I was reviewing AppCoda’s Beginning iOS 10 Programming with Swift when the new versions of XCode, Swift, and iOS were released. The publisher also updated the book, so I decided to switch to the new material.

Instead of discarding the initial review and starting over again from scratch, I decided to publish what I’ve done already and will delete this older content once I reach the same point in the new book (Ch 14). I will leave out the screenshots for this older material as well, but will have plenty in the new material.

I intend to update this review once a week, even though it is the holiday season right now.  Please follow this post so you can see when it is updated.  Now on to the review.

Title: Beginning iOS 10 Programming with SwiftBeginiOS10Prgm
Author: Simon Ng
Published: AppCoda publisher
Price: NO LONGER AVAILABLE
Length: 612 pgs (PDF) (30 chapters)
Website: www.appcoda.com

By Mike Hubbartt, © Copyright 2017, All Rights Reserved.

This book is for Swift 3, Xcode 8 and iOS 10, and the intended audience is people without programming experience as well as people wanting to learn the Swift programming language.

I’ve been a programmer a long time, and have dabbled in mobile development awhile but have not been happy with the iOS tutorials I found until now. I came across ‘Beginning iOS Programming with Swift’ after searching for iOS tutorials on Yahoo, and started following the online book. AppCoda provides part of the course at no charge, which is a nice approach and similar to other publishers providing free chapters to interest prospective buyers. After going through the first five chapters, I had created two new iOS apps fairly easily, so I contacted AppCoda and got the book so I could complete the course.

Before we get started, I want to point out that this book used Xcode 8.0. If you upgrade to Xcode 9 and iOS 11, so if you already upgraded to both, you may want to contact the publisher to see when the update to this book will be done.

During development, you need to select a target version of iOS – my mini tablet just has 9.3.5, but my old iPhone 5 has 10.3.3, so I used that as the default target iOS initially. Now lets get started with the review.

IMPORTANT NOTE!! My review was done using the iBook version of the book, not the PDF, so I use those page numbers in my references. Please be aware there are a lot pages in the iBook version of documentation than in the PDF version, so the page numbers do not match up.

THE BOOK
The first three sections are: Preface, Ch 1:Getting Started with Xcode 8 Development, and Ch 2:Swift Playgrounds – all important if you’ve never developed, or new to development with a Mac. I’ve done both, but I still read over the material and did find it useful and accurate for setting up a development environment for Macs. Being anxious to create an actual iOS app, I pressed on to chapter 3 so I could see how easy it is to build an app.

IMPORTANT NOTE: The list in the table of contents at the start of the iBook lists the sections, but it shows Preface as the first. The actual chapters are not part of the items in the TOC, which is a small item I would suggest the author change, as well as update any chapter titles that might have been updated since initial publication.

Chapter 3: Build Your First App

This chapter has you build a simple Hello World app – the task most books have when teaching a programming language. Simon has you build an app with a single button, plus the code needed to tie the button to functionality.

The author gives you the specific steps you need to follow to create this app. It really is easy, and all I needed to do was follow the steps to build a Hello World app:

  1. Create a newXcode project.
  2. Select a template for your new project (Single View Application).
  3. Choose options for your new project (the book has the options plus what you enter for them – nice).
  4. Save the project (pick a location on your computer – I decided to use different ones for each book project).
  5. After selecting Next and Create, Xcode opened my new project (See below). The author points out the importance of learning a development environment, and I followed his advice and explored the Xcode Workspace. The author explains how to use the Xcode Simulator to run Xcode projects, and uses large and clear graphics to show what to select to see a project execute. I have an iPhone 5s, so I took the opportunity to change the Xcode Simulator to use that instead of the default iPhone 6. You could use newer iPhones or tablets too.
  6. To build the button for the Hello World project, you need to switch to the Interface Builder, where buttons and other interface items (like lists, other controls, etc are available to the developer).  I selected the Button and moved it to the middle of the View Controller area of the screen.  I positioned the button in the middle of the screen (easy the the Xcode alignment guideline, as shown in Fig 6), then renamed the button (per the book). The author says you can already test the app at this point so I did. It did take a few minutes for the Simulator to get started and render the iPhone with the new app, but it did – be patient. At this point, you have created a simple iOS app with a simple button that does nothing, but you still have created a app.NOTE: The author makes a great point about iOS development. The code and UI for apps are separate – this means you spend less time learning how to create a UI and more time on the layout and logic of app design. Sweet.
  7. To add code to the the app, which is executed when the button is selected, you need to switch to the ViewController.swift file.  I added the code is the first IBAction function (the other two functions were added later to extend my learning). As you see, Swift coding isn’t difficult. The book explains what each part of the simple code does, not too deep to slow you down at this point, but enough to understand what is happening.
  8. Now you need to connect the code you wrote in step 7, to the UI you created in step 6. This is easy. Just switch back to the Interface Builder, select the button and drag it to the View Controller under the View Controller Scene at the left of the UI.Now you can test how the code works with the button you added. This is better than the simple test you did in step 6, as you get to see your app do something. Run it with the simulator and there you are. Your first iOS works. Sweet.
  9. I wanted to learn more, so I did the end-of-chapter exercise and added a few extra buttons plus added two new functions to display different messages than the first button. It was intuitive and easy, and something I suggest you do too. The only way you get better as a developer is to learn all the ranges you have at your disposal, so play time in this case is actually very productive. Now play.NOTE: As this Hello World is very basic, I only used the Simulator to test it. I will deploy more advanced apps developed later in this book, using my iPhone and iPad Mini. The iPad mini will require an older version of iOS, so I will describe how easy that is to set before creating and deploying my apps.

Chapter 4: Hello World App Explained

This chapter goes into detail into what you just built. You must read this, as it clarifies the other options you have. I kept my Hello World app open while reading the chapter, and checked out the options as I followed along in the book.

The material in this section was just as useful as the earlier chapters, and keeping it separate from the first app you develop means you don’t get bogged down in language details while creating your first app, yet you still get the technical information needed to back up the process of creating an iOS app. I like this approach – very easy to make progress, while still learning detailed processes.

Chapter 5: Introduction to Auto Layout

Auto layout is where the UI elements can be arranged and can handle the different sized screens available to iOS apps. iPhone 4s – 8s use different screen sizes, as do tablets, so this is important unless you only want to develop apps for your own use.

I’m not going to spend a lot of time in this chapter, since it is no longer the way you develop apps for different devices. The author includes it so you see how it was done, but the next chapter gets into stack views, which is the newer method for developing multi-device apps.

To use auto layout, you set constraints to the sides and top or bottom of the screen, which help retain formatting when a device is turned on the side or when devices with different-size screens run your app. It takes a bit of work, but it works. Now on to the next chapter.

Chapter 6: Designing UI Using Stack Views

In iOS9, Apple introduced Stack Views to layout UIs. What is a Stack View? I asked that myself. As the author says:

“The stack view provides a streamlined interface for laying out a collection of views in either a column or row….
You can embed multiple UI objects into one by using stack views…
The stack view manages the layout of its subviews and automatically applies layout constrains for you. That means, the subviews are ready to adapt to different screen sizes. Furthermore, you can embed a stack view in another stack view to build more complex user interfaces.”
– Simon Ng, Beginning iOS Programming with Swift, Page 87

NOTE: This doesn’t eliminate the need for auto layout. You still need to define layout constraints for stack views. This is the chapter where we learn how to develop more advanced iOS apps.

Creating a New App

  1. You need to create a new project for this chapter. The author suggests StackViews, which is the same name I used for the directory to hold the new project. He provides the answers you need to create the project, so no guessing at this point.
  2. You will need some images (3 images, each in 3 different sizes), which he provides as a download. Xcode groups images in an asset catalogue (called Assets.xcassets in Xcode).
  3. Download the images and drag them to in the AppIcon list as described in the book. Once you need to access each image, you don’t need to specify size which is used – iOS does that for you.
  4. Open Main.storyboard for this project to add two labels to the new app. Drag a Vertical Stack View object (from the Object Library at the bottom left of Xcode) to the storyboard view controller.
  5. Now drag a label object and drop it on top of the stack view. Rename the label per the book, then resize it and change the font color as well.
  6. Drag a 2nd label object and drop it on the same stack view. Rename the second label, per the book. By default, labels left-justify, so change the stack view property from Fill to Center to center align both labels.
  7. Now add 3 images to the view. You place the 3 images side-by-side, then you will use another stack view to group them together. Add another stack view to the view and add the images to that stack view.
  8. Now you combine both stack views so all of the elements are positioned as a unit.
  9. Add constraints. This is where the free online material differed from the purchased book. The book says:

    “Now click the Pin button in the layout button. Set the space constraints of the top, left and right side to 70, 0 and 0 respectively. When the constraint is enabled, it is indicated by a solid red bar. Then click the “Add 3 Constraints” button to add the constraints.”- Simon Ng, Beginning iOS Programming with Swift, Page 100

    I found this unclear, so I looked around and noticed the button looking like a cutout of a tie fighter in the bottom right part of Xcode, so I selected it and was able to set the constraints as directed.

  10. The book then says that there will be problems positioning the stack view. I got (very) lucky and had no issues. Sweet.
  11. Now preview the app on other devices. It looked good, except some issues truncating the top label – easily fixed. I again got lucky and had no issue with the aspect ratios of each image (they did not appear stretched), which was due to my playing around with the app before receiving the book from the publisher. Compared to the first app, I was impressed.Per the book, I fixed the title truncation (very fast easy fix) and tested it and it worked fine.
  12. Add another 2 labels to the view, then add both to a stack view. Following the book, very simple. This app is starting to look like a real app. I adjusted position (relative to the bottom of the device) and size and spacing to keep the buttons looking good.
  13. Now it was time to learn about a new (since iOS 8) UI design concept: Adaptive Layout, which lets apps adapt the UI to particular devices and device orientation. You need Size Classes to achieve adaptive layout.

    “A size class identifies a relative amount of display space for both vertical (height) and horizontal (width) dimensions. There are two types of size classes: regular and compact. A regular size class denotes a large amount of screen space, while a compact size class denotes a smaller amount of screen space.”- Simon Ng, Beginning iOS Programming with Swift, Page 111

    “By describing each display dimension using a size class, this will result in four abstract devices: Regular width-Regular Height, Regular width-Compact Height, Compact width-Regular Height and Compact width-Compact Heigth.”- Simon Ng, Beginning iOS Programming with Swift, Page 112

  14. Size Classes made it easy to position UI elements, or hide them on certain devices. Sweet.

Chapter 7: Introduction to Prototyping

“A prototype is an early model of a product used for testing a concept or visualizing an idea.”
– Simon Ng, Beginning iOS Programming with Swift, Page 119

I’ve created many prototypes before and during projects over my career as a developer, as they help the customer see what you intend to deliver. Unfortunately, while prototypes can prevent scope creep with some customers. they encourage scope creep with other customers.

Scope creep is where projects change as work progresses, as customers decide to ask for more features or functionality. Scope creep is an enemy of any Project Manager, as it destroys estimated project timelines. You can’t prevent everyone from asking for more, but you try to get them to accept adding those after the initial project rollout or update.

With traditional enterprise-class software projects, writing a prototype on paper or in PowerPoint or on a whiteboard is usually faster than creating a software prototype. You draw the basic UI elements of each page and show the flow between design elements/pages. When you need to add functionality to an existing site or system, you just need to prototype the new functionality to demonstrate it works.

This chapter of the book has a list of good tools to help prototype iOS apps, including: Marvel, Photo.io, Flinto, Principle, InvisionApp, POP, Sketch, Adobe Experience Design and Keynote. Of these, only the last four are described – no worries as well all know how to Google. For this review, the prototype tool I used was POP (Prototyping On Paper), which lets you create working prototype without writing any code – a real timesaver when preparing a quote for a client.

I downloaded from the iTunes store and installed on my iPhone, then grabbed the app prototype same the author provided (1.6M file available as a link in the book). I added the downloaded images from the author to my iPhone, opened POP, created a new project, then linked the pages together. Pressing the Play button allowed me to navigate through the prototype screens, which would look very good and useful to any client. Then, you just need to make the app in Xcode, test, and demo the working product to a customer. Nice.

I like this included. Prototyping isn’t included as part of Xcode (wish it was, Apple) but the tools mentioned in chapter 7 are worth time learning. I’d suggest initially POP and Adobe Experience Design, but the others are very good too.

Chapter 8:Creating a Simple Table Based App

“First of all, what exactly is a table view in an iPhone app? A table view is one of the most common UI elements in iOS apps. Most apps (except games), in some ways, make use of table view to display content. The best example is the built-in Phone app. Your contacts are displayed in a table view.”
– Simon Ng, Beginning iOS Programming with Swift, Page 130

This is where you create your third iOS app. After creating a simple table project in Xcode, I added a single table view to the view, then made the table view take up the entire view. Next, I set the Prototype Cells to 1. Why?

“Prototype cells allow you to easily design the layout of your table view cell. You can think of it as a cell template that you can reuse in all of the table cells.”
– Simon Ng, Beginning iOS Programming with Swift, Page 133

The app created in this chapter uses the UIKit framework, which provides classes to construct and manage the UI app interface. All objects in the Xcode Interface Builder Object Library are in UIKit.

The author mentions in this chapter he is not discussing classes and methods yet – OOP elements that some find confusing – but he does cover them later. A good idea when the audience is new to development.

Following the instructions, I created a simple table, using a list instead of a database, similar to the iOS Contacts app. Not terribly difficult, however I forgot to set the prototype cell identifier to Cell, so I had an error to track down – an email to AppCoda and I had the answer how to fix the issue, so I was back at it again. Good example, but now I am looking forward to using a database or data source that isn’t a fixed array list and I want to see how to add individual images to each item in the list – the second item is covered in chapter 9.

Chapter 9: Customize Table Views Using Prototype Cell

This is where we built a real app called FoodPin. After closing the SimpleTable app, I created a new project, similar to the project in chapter 8 but using UITableViewController and using individual images for each restaurant displayed in the app. It was easy using Swift, which is well worth learning for novices as well as experienced developers.

This app has custom labels for each cell, which I created by dragging 3 Label objects to the cell, grouping them with a stack view, then grouping the new stack view and the cell image in another stack view. Simple. Then, Simon points out an important fact about iOS development:

“By connecting the source code with the UI objects, we can change the values of UI objects dynamically.

This is a very important concept in iOS programming. Your UI in storyboard and code are separated. You create the UI in Interface Builder, and you write your code in Swift. If you want to change the value or properties of a UI element (e.g. label), you have to establish a connection between them so that an object in your code can obtain a reference to an object defined in a storyboard. In Swift, you use @IBOutlet keyword to indicate a property of a class, that can be exposed to Interface Builder.”
– Simon Ng, Beginning iOS Programming with Swift, Page 391

We created a new class for the project, where we defined variables for all four items in each cell (Name, Location, Type and ThumbnailImage) using @IBOutlet.

“@IBOutlet is used to indicate a property that can be connected with a view object in a storyboard.”
– Simon Ng, Beginning iOS Programming with Swift, Page 393

You use these outlets to change font characteristics or events to be triggered when a button is selected. Handy and something you must understand. You also need to set the prototype cell to use the custom class you create, which is also simple. The chapter also explains how to set the images to appear circular instead of square – a few extra steps, but the presentation is worth it. We also set the restaurant name, location and type values to be dynamically displayed, which was fairly easy too.

Chapter 10: Interacting with Table Views and Using UIAlertController

In this chapter, we select an item in the view, just like selecting a contact name in the Contacts app. We also are exposed to UIAlertController, which is commonly used to display iOS alerts. In this chapter, we improve the FoodPin app by using individual images and rounding them to improve the look of our app. We also add three labels for each restaurant (name, location and type) to each row in the table, plus add three arrays to provide custom information for each restaurant.

No real problems following along with the directions in this section. I did copy and paste some of the code to save time, but I did read the information on everything new we are exposed to, and suggest you do so too. After getting the custom information to show in each line, we add a button to show a checkmark beside a restaurant – to show when a restaurant is selected. Then we addressed a known bug on reusing cells, plus add a line of code to deselect a cell once an option is chosen from the new popup list.

Good chapter. A LOT more Swift coding was covered. Not too much, but more than earlier chapters. Now on to chapter 11.

Chapter 11: Table Row Deletion, Custom Action Buttons, Social Sharing and MVC

According to Wiki (https://en.wikipedia.org/wiki/Model–view–controller):
Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces on computers. It divides a given application into three interconnected parts. This is done to separate internal representations of information from the ways information is presented to, and accepted from, the user. The MVC design pattern decouples these major components allowing for efficient code reuse and parallel development.

I’ve used this architectural pattern doing web development, but was unaware this was also popular for desktop GUI development. Sweet. I would suggest you read more about this pattern if you even think you may do web development some day.

“Separation of Concerns (SoC). The concept is pretty simple. Here, the Concerns are different aspects of software functionality. This concept encourages developers to break a complicated feature or program into several areas of concern so that each area has its own responsibility. The delegate pattern, that we explained in the earlier chapters, is one of the examples of SoC.

The model-view-controller (MVC) concept is another example of SoC. The core idea behind MVC is to separate a user interface into three areas (or groups of objects) that each area is responsible for a particular functionality. As the name suggests, MVC breaks a user interface into three parts: Model, view and controller”
– Simon Ng, Beginning iOS Programming with Swift, Page 446

To illustrate MVC using an iOS app, consider the SimpelTable app developed in chapter 8. The restaurantNames object is an array and is the model, the UITableView object is the view, and the UITableViewController is the controller.

On to deleting rows in a view. In iOS apps, data in a view is usually deleted by swiping across the row in the view. A good example: the iOS Mail app. The Swift code needed to delete a row and refresh the view is simple:

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath:IndexPath) {
// enables deleting a row in a table view
// Now u can swipe a row and a delete button is visible, but not enabled

// this code allows deletion of data from the 4 arrays:
if editingStyle == .delete {
// Delete the row from the data source
restaurantNames.remove(at: indexPath.row)
restaurantLocations.remove(at: indexPath.row)
restaurantTypes.remove(at: indexPath.row)
restaurantIsVisited.remove(at: indexPath.row)
restaurantImages.remove(at: indexPath.row)
}

print(“Total item: \(restaurantNames.count)”) // for debugging purposes
for name in restaurantNames {
print(name)
}
tableView.reloadData() // refreshes the view to show revised data
}

Something I like about this example: being able to access Twitter and other social media. I added the UIActivityViewController code to enable tweeting from the FoodPin app, including embedded images, logged into Twitter on the Simulator and tweeted from the simulation of FoodPin – it worked. Sweet. Talk about a great real world example! One suggestion I’d make regarding this functionality, is mention it is a test in your tweet plus include @AppCodaMobile in the tweet so the book publisher is notified you are testing this functionality of the book.

Chapter 12: Introduction to Navigation Controller and Segue

Navigation controllers let you drill down into content. Using our FoodPin app as an example, selecting a restaurant in the view, a navigator would drill down into pertinent information on that restaurant.

“Generally, you combine a navigation controller with a stack of table view controllers to build an elegant interface for your apps.”
– Simon Ng, Beginning iOS Programming with Swift, Page 484

Yes, it’s finally time to have more than a single view in our FoodPin app. Yay, lol.

“add more view controllers in the storyboard, link them up, and define the transitions between them. All these can be done without a line of code. When working with storyboards, scene and segues are two of the terms you have to know. In a storyboard, a scene usually refers to the on-screen content (e.g. a view controller). Segues sit between two scenes and represent the transition from one scene to another.
– Simon Ng, Beginning iOS Programming with Swift, Page 485

To make storyboards easier to use, large ones can be broken up and linked using storyboard references.

I followed the directions in this chapter, using the Interface Builder to add a navigation interface to my FoodPin app. It was easy and took no coding to get it to work. After adding the navigator, I used the Interface Builder to add another view controller to display restaurant details. I then added a segue to connect the first controller to the detail controller, also using Interface Builder. Now I had two view controllers and a navigation controller, and now I needed to share the first images with the details view controller, so it was time to add another class.

“A segue manages the transition between view controllers, and contains the view controllers involved in the transition.”
– Simon Ng, Beginning iOS Programming with Swift, Page 674

This is the Swift code from the book for the segue:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == “showRestaurantDetail” {
if let indexPath = tableView.indexPathForSelectedRow {
let destinationController = segue.destination as! RestaurantDetailViewController
destinationController.restaurantImage = restaurantImages[indexPath.row]
}
}
}

CH 13: Introduction to Object Oriented Programming

Swift and Objective-C are OOP languages, where you create and use objects. As the author points out, some of the iOS SDK objects we’ve already used up to this point include the UIViewController, UIButton, UINavigatorController and UITableView. Essentially, one uses OOP to develop complex applications using small building blocks, where each has a specific purpose. In OOP, you create a class and use that class as a blueprint to create objects (also called instances) with methods (to provide functionality) and properties.

In the FoodPin app, we have five arrays holding individual types of restaurant data. In this chapter, we modify that.  This is the Swift code used to make that new class:

class Restaurant {
var name = “”
var type = “”
var location = “”
var image = “”
var isVisited = false

init(name: String, type: String, location: String, image: String, isVisited: Bool) {
self.name = name
self.type = type
self.location = location
self.image = image”
self.isVisited = isVisited
}
}

The five properties for the new class are name, type, location, image, and isVisited. The 1st four properties are declared as blank strings (“”), while the 5th is boolean. init() defines the object initializer, which sets the initial property values for each new object created with this restaurant class. The restaurant data is now grouped by restaurant, instead of by number – data in the real world is kept in database tabes, grouped by a key value that is called instead of a relative position in an array. The code for this is:

var restaurants:[Restaurant] = [
Restaurant(name: “Cafe Deadend”, type: “Coffee & Tea Shop”, location: “Hong Kong”, image: “cafedeadend.jpg”, isVisited: false),
Restaurant(name: “Homei”, type: “Cafe”, location: “Hong Kong”, image: “homei.jpg”, isVisited: false),
Restaurant(name: “Teakha”, type: “Tea House”, location: “Hong Kong”, image: “teakha.jpg”, isVisited: false),
Restaurant(name: “Cafe loisl”, type: “Austrian / Causual Drink”, location: “Hong Kong”, image: “cafeloisl.jpg”, isVisited: false),
Restaurant(name: “Petite Oyster”, type: “French”, location: “Hong Kong”, image: “petiteoyster.jpg”, isVisited: false),
Restaurant(name: “For Kee Restaurant”, type: “Bakery”, location: “Hong Kong”, image: “forkeerestaurant.jpg”, isVisited: false),
Restaurant(name: “Po’s Atelier”, type: “Bakery”, location: “Hong Kong”, image: “posatelier.jpg”, isVisited: false),
Restaurant(name: “Bourke Street Backery”, type: “Chocolate”, location: “Sydney”, image: “bourkestreetbakery.jpg”, isVisited: false),
Restaurant(name: “Haigh’s Chocolate”, type: “Cafe”, location: “Sydney”, image: “haighschocolate.jpg”, isVisited: false),
Restaurant(name: “Palomino Espresso”, type: “American / Seafood”, location: “Sydney”, image: “palominoespresso.jpg”, isVisited: false),
Restaurant(name: “Upstate”, type: “American”, location: “New York”, image: “upstate.jpg”, isVisited: false),
Restaurant(name: “Traif”, type: “American”, location: “New York”, image: “traif.jpg”, isVisited: false),
Restaurant(name: “Graham Avenue Meats”, type: “Breakfast & Brunch”, location: “New York”, image: “grahamavenuemeats.jpg”, isVisited: false),
Restaurant(name: “Waffle & Wolf”, type: “Coffee & Tea”, location: “New York”, image: “wafflewolf.jpg”, isVisited: false),
Restaurant(name: “Five Leaves”, type: “Coffee & Tea”, location: “New York”, image: “fiveleaves.jpg”, isVisited: false),
Restaurant(name: “Cafe Lore”, type: “Latin American”, location: “New York”, image: “cafelore.jpg”, isVisited: false),
Restaurant(name: “Confessional”, type: “Spanish”, location: “New York”, image: “confessional.jpg”, isVisited: false),
Restaurant(name: “Barrafina”, type: “Spanish”, location: “London”, image: “barrafina.jpg”, isVisited: false),
Restaurant(name: “Donostia”, type: “Spanish”, location: “London”, image: “donostia.jpg”, isVisited: false),
Restaurant(name: “Royal Oak”, type: “British”, location: “London”, image: “royaloak.jpg”, isVisited: false),
Restaurant(name: “CASK Pub and Kitchen”, type: “Thai”, location: “London”, image: “caskpubkitchen.jpg”, isVisited: false)
]

After making the code changes to reference restaurants.*, I ran the sample in the simulator and it worked just fine. Introducing OOP concepts and making this change was the purpose for this chapter. One thing I want to point out: at the end of this chapter, the author includes some links to Swift OOP programming. I am impressed he included a link to a free online course from MIT. MIT is one of the best sources for free college classes, and I rarely see anyone link to them, so kudos to Simon.

 

========================================================================

THE NEW REVIEW MATERIAL BEGINS HERE

========================================================================

Title: Beginning iOS 11 Programming with SwiftBeginiOS11Prgm
Author: Simon Ng
Published: AppCoda publisher
Price: $39, $69, $149
Length: 833 pgs (PDF) (30 chapters)
Book Website: www.appcoda.com/swift

By Mike Hubbartt, © Copyright 2017, All Rights Reserved.

I’ve been a programmer a long time, and have dabbled in mobile development awhile but was unhappy with the iOS tutorials I found on the internet. I came across ‘Beginning iOS 10 Programming with Swift’ after searching for iOS tutorials on Yahoo, and started following the online book, since the developer provides part of the course for free. Other publishers also provide free chapters to interest prospective buyers, since you can try before you buy.

I went through the first five free chapters and had created two new iOS apps fairly easily, so I contacted AppCoda and got the book so I could complete the course. Two weeks after starting the iOS 10 course, Apple released an OS and development tool update, so the publisher released an update to the course. I got the new course and started over, so this review will be from beginning to end of the new course material.

This review covers “Beginning iOS 11 Programming with Swift”, which is for Swift 4, Xcode 9 and iOS 11. The intended course audience is people without programming experience as well as experienced developers wanting to learn the Swift programming language.

CHAPTER 1: The Development Tools, the Learning Approach and the App Idea

This chapter covers what you need to get started: essentially a fairly modern Mac with Xcode. Not too expensive these days, and the only way to go to develop iOS apps, The material is good, plenty of pictures to guide the users, and it should put new developers at ease before they start creating their first app.

CHAPTER 2: Your First Taste of Swift with Playgrounds

This gets you started writing Swift code using Xcode playgrounds. . When I started reviewing “Beginning iOS 10…”, I said that this chapter was useful, but inferred it was unnecessary for experienced developers. The author has enhanced this chapter for this new release of the book and, while it does have good setup information useful for non-developers, the rest of the chapter is worth reading for experienced programmers that are new to programming on a Mac.

Why use Swift instead of Objective-C? Swift is easier to learn as the syntax is closer to English. An example from the book:

Fig2-1 Objective-C vs Swift

Fig 2-1 Objective-C vs Swift

I’ve used Xcode for a number of years, but I like how the author gives an intro to using Playgrounds. Playgrounds are places where you test pieces of code – AKA snippets – during learning or development. Something true about learning to program that is shared with music: you can’t learn how to do it by merely reading theory about it.

The author gets into writing Swift code with Playgrounds in chapter two, but not in detail until covering how to install Xcode for people new to development. He explains the Playground environment so new developers understand how to test their code snippets during the course of this course – good idea.

The Swift coding topics covered after Xcode setup are:

  • constants, variables, and how/when to declare types
  • control flow (looping and using switch)
  • collections (arrays and dictionaries)
  • optionals

Swift can infer what type to use for a variable, but specifying by declaring the types makes code easier to read and helps avoid type issues.

Flow control statements are if-else and switch. I particularly like Swift’s range operator for lower bounds and upper bounds, as it simplifies coding when using switch statements. Collections hold groups of data, and arrays are familiar to developers familiar with other programming languages. Like Java arrays, Swift arrays begin with element 0. Swift has the familiar for loop, but also has a for-in loop to move through dictionary elements.

What are dictionaries? They are like arrays, but they use a key to reference each stored value instead of a number relative to the index. The key can be specific to the data, so this can be quite useful when writing apps that use keys like ISBN numbers for books, account numbers for clients, etc.

The code example for creating dictionaries is simple but useful for people new to them. The last code topic covered in this chapter is on optionals. Optionals let you specify variables without default values, which makes you verify the variable has data before you access it.

Fig 2-2 Optional Var Checking Unwrapping

Fig 2-2 Optional Variable Checking Using Unwrapping

 

Fig 2-3 Optional Var Checking Binding

Fig 2-3 Optional Variable Checking Using Binding

Time to get started building an app, so let’s move on to chapter three.

 

CHAPTER 3: Hello World! Build Your First App in Swift

Every new developer knows what a “Hello World” program is: it’s the first thing you write when learning a new programming language. In this chapter, we create our first Swift iOS app and we call it Hello World. We worked with a Playground in chapter two, but now we will create a project and test it with the Xcode Simulator.

The book uses screenshots with the step-by-step process to show how you create the HelloWorld project. Not difficult at all. When finished, you should see something like this:

Fig3-1 New HelloWorld Project
Fig 3-1 New HelloWorld Project

Make sure you take time to get familiar with the Xcode project screen. You are expected to know where to find each area as the course progresses. The editor area in the center changes, depending on which design element (AppDelegate.swift, ViewController.swift, Main.storyboard) is selected at the left part of the project. The right side of the project is the utility area, where you select properties. You can expose or hide the leftmost and rightmost areas as well as the debug area for a project – this is at the top rightmost part of the Xcode project screen:

Fig3-2 Three Areas of an Xcode Project
Fig 3-2 Three Areas of an Xcode Project

After creating a basic project and a new iOS app, you can run it in the Simulator. One note: the first time you run the Simulator, it takes a while to start, so be patient. The Xcode control to run an app is the right-pointing arrow at the top left side of Xcode:

Fig 3-3 How to Run Apps in Simulator
Fig 3-3 How to Run Apps in Simulator

In this chapter, Simon points out something nice in the new version of Xcode 9: you can now run multiple simulators at the same time. Now that I like, as you may want to have an Apple Watch sim going the same time as iPhone and iTablet simulators.

Now it’s time to add an interface to the HelloWorld app. The book points out you can easily add one or more views and link them together without writing a line of Swift code. It’s similar to some RAD products like Power Builder and Lotus Notes. Xcode uses one View Controller per iOS app screen. The Interface Builder is shown below, with the View Controller in the middle, with the Button object in the center of the View Controller:

Fig 3-4 Xcode Interfact Builder Screen
Fig 3-4 Xcode Interface Builder Screen

I ran the Simulator after adding the Hello World button and saw this:

Fig 3-5 Simulator with Hello World Button
Fig 3-5 Simulator with Hello World Button

That’s it. I didn’t need to write any code to make a simple iOS app. It is simple. Hopefully this encourages people with good ideas but no programming experience to try to make something for themselves or for others.

The next step in the book is to add some code to make the Hello World button do something. We access the ViewController.swift file in Xcode and add the following Swift code to have the button say Hello World:

@IBAction func showMessage(sender: UIButton) {
 let alertController = UIAlertController(title: "Welcome to my first app", message:
 "Hello World", preferredStyle: UIAlertControllerStyle.alert)
 alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
 present(alertController, animated: true, completion: nil)
 }

I want to echo the tip the author makes about entering code vs copying and pasting.  The easiest way to learn is to do, not copy.  Take the time to type, as you will see how easy it is to make mistakes, and when you fix them you learn a bit more. My 2 cents on developing:

A developer writes their own code, they don’t copy and paste and modify someone else’s code – that isn’t creating code, it’s appropriating.  If you want to work as a developer, you better remember this tip, because professional developers do not look fondly on people copying and claiming the work of another person.  It isn’t ethical.

 

Now you need to connect the Hello World button to this new code. Select Main.storyboard in Xcode, select the Hello World button and hold down the Control key and drag up to the yellow View Controller object at the top of the View Controller, then select showMessageWithSender: option in the popup box.

Fig 3-6 Connect Button and Swift Code
Fig 3-6 Connect Button and Swift Code

Run the Simulator again and now you see that the button does something:

Fig 3-7 Working Hello World Button
Fig 3-7 Working Hello World Button

There are a couple of exercises at the end of the chapter. I wanted to see what I learned, so I added 3 more buttons, which is what exercise 1 is, however I wanted to use different messages so I added additional code to ViewController.swift and linked it to each button. It was fun, and the best way I know to really learn. If you want to learn how to write code or develop apps, you must do it, mot just read about it. I strongly encourage people to do both exercises and play around on your own. It helps.

 

CHAPTER FOUR: Hello World App Explained

This chapter explains in detail what happens in the first app you create: Hello World. Take time to go over this chapter, especially if you are new at learning to program, as the explanations here lay a foundation that grows in future chapters.

How does the interface you build connect to Swift code that you write? It is important to understand this now, so consider the TV remote example the author uses:

“The user interface in the storyboard is the interface, while the code is the implementation. The user interface objects (e.g. button) communicate with the code via messages.

Specifically, if you go back to the Hello World project, the button you added in the view is the interface. The showMessage(sender:) method of the ViewController class is the implementation. When someone taps the button, it sends a showMessageWithSender message to ViewController by invoking the showMessage(sender:) method.”
– Simon Ng, Beginning iOS 11 Programming with Swift, Page 95 & 96

As the author points out, this demonstrates the OO concept of encapsulation. The specifics of what happens is hidden when the button is pressed. For example, the programmer could choose to send an email as well as display “Hello World” when the button is pressed, and the button pusher wouldn’t know.

What happens when the Hello World button is pressed? The button is event-driven, meaning that it does something when the button is pressed or released. In this app, we made the action occur when the button was released. This illustration shows the process:

Fig 4-1 What Happens in Hello World App
Fig 4-1 What Happens in Hello World App

We used a method to specify the message we displayed when the button was released. Methods provide functionality to objects – they make things happen. In this example, the class ViewController has a method called showMessage() – Swift methods are declared with the func keyword, and the @IBAction keyword in showMessage() connects source code you wrote to the interface button object you added using the Interface Builder.

Fig 4-2 ViewController and showMessage
Fig 4-2 ViewController and showMessage

This chapter is loaded with great information for new developers, as well as people learning Swift. Take a day to cover the material the first time, then take a second day before progressing on to chapter 5. You will learn important information that will help you further into this course.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s