iOS Development Help Site
By Nancy Liu
Dept. of Computer Science
iOS Help Site Navigation
iOS Help Site Home
Swift: Basics and Intros
Swift vs. Other Languages
Language Basics
Setup: Getting Started in Xcode
Playgrounds
Projects
Playground vs. Project
Stuck?
Projects: Basics in Xcode
The Interface Builder
Controllers
Views
Additional Features
Projects: Not as Basic
Segues
Delegating Protocols
Core Data and User Defaults
Multithreading
KVO
Extras
Introduced in Class
Others

Other useful links
Key Dates 2016-17
Final Exam Schedule
Register your i>clicker
Unicode
ASCII (Wikipedia)

Not as Basic

Here are structures and functions of Swift that are not as "basic". Because of the depth that would be required and the infinite number of situations, I will not go into step-by-step tutorials or code. I'll go over the essentials, namely Segues, Delegates, and Protocols (in case lecture demos didn't fully cover it for you).

For everything else, I'll do my best to give you resources or pointers to locations that would be good to look at if you'd like to spend the time.

 

Segways nyoomm

Segues are a very, very, very important part to app-building. So important, that I will do my best to go into detail about them. You will be using segues for both the homeworks and projects (you kind of need them, a little). The concept of segues - sending and receiving information from one view to another - is so important that it is the basis for many other functions in Swift app-building.

Below I'm going to be referring (showing screenshots) to the Developer's Library entry for segues, because it really is that good of a source.

The definition of a segue is a "transition between two view controllers in your app’s storyboard file". It works exactly as that sounds. A segue can be seen as "source object A leads to destination B", where that object can be anything you want: a button, an interactive row in a table view, a tab on a tab bar controller, etc..

Important: a segue can optionally pass information with it when it moves from A to B. If B needs specific information from A that the segue interaction itself provides (ex: if you push a button, does destination B need the text displayed on the button?), the segue is where you would carry that info.

How you first create a segue transition is by control-dragging from your source object A to the destination B that you want to have displayed. Once that's completed, you should see an arrow that points from the view controller of A to the view controller of B.

 

Creating a segue...

And the resulting relationship, shown by the blue arrow.

 

As mentioned before, there is still code that accompanies creating a segue like above. When you create a new .swift file, the default template for the file will have a section where you can modify the  prepareForSegue function, which is the segue. If a view controller is a segue source and its destination view controller needs info, you'll need to modify the source VC's .swift file accordingly to carry the info.

For instance, using a sample similar to the lecture demo (this is abbreviated from an old homework):

 ESCAPE='HTML'

Here, we have a segue that executes whenever a row in a table view is selected, as shown by the " operatorIndex = ...". In this example, the segue carries the selected row's index to the destination, where the destination .swift file's operatorChosen  variable makes use of the passed operatorIndex.

For general purposes, we can do without the lines that include "operatorIndex = ... and "destination.operatorChosen...".

And of course, you will need to replace _YOUR_SEGUE_NAME_HERE_ with the name of the segue that this prepareForSegue is going to be associated with, and _DESTINATION_VIEW_CONTROLLER_ with the name of the view controller that is the destination of the segue (this means that your view controllers and segues have to have names on them if you want to use them).

However, do note that if there is nothing in the body of the if statement (where "destination.operatorChosen" is), Xcode won't be happy. In the case where you don't need to pass information and simply want to transition to a display window, you could print something (such as a blank line or "").

 

SEGUES: RECOMMENDATIONS

If you feel that using a segue isn't necessary and may overcomplicate a simple transition, or you feel like being traditional, here's an article by Tim Ross: To Segue or Not to Segue.

 

Protocols + Delegates

Protocols and delegates essentially come as a pair (in the context of this class, at least). By the Developer's Guide, the definitions are:

Protocol: defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.

• Delegation: a design pattern that enables a class or structure to "hand off" (or delegate) some of its responsibilities to an instance of another type. This design pattern is implemented by defining a protocol that encapsulates the delegated responsibilities, such that a conforming type (known as a delegate) is guaranteed to provide the functionality that has been delegated. Delegation can be used to respond to a particular action, or to retrieve data from an external source without needing to know the underlying type of that source.

 

Big text and official definitions if you need it. From my experience with this class:

• Protocol: defines the functions that need to be defined, similar to an  interface in Java.

• Delegation: a function that conforms to a protocol (is one of the functions that needs to be defined), and will often times interact with an instantiated delegate variable. The delegation can receive information from its delegate, and do things with the information and/or give the delegate new information to carry. Also, the delegation can "transcend" the scope of its .swift file, because of the protocol it's conforming to.

• Delegate: a variable that is instantiated in the same .swift file that also has its associated delegation function. The delegate is essentially a carrier of information that allows the delegation to move information around.

That also probably didn't help much. Let's see if an example will.

 

PROTOCOLS AND DELEGATES: AN EXAMPLE

Okay. So, let's use a mail metaphor and say we have two files: ReceiveMailViewController.swift and SendMailViewController.swift. What we want to do is send mail from one person to another, using protocols and delegates.

Here's what we need:

• An envelope: this is the delegate we'll create (instantiate) in SendMail

• The mail contents: this is the information the envelope (the delegate) will carry

So if we want to send mail, we first have to put the mail into an envelope, and then send the mail to the recipient. We can create a "send mail" protocol that will have to have defined delegations, in SendMailVC.swift:

 ESCAPE='HTML'

Keeping to the mailing analogy, whichever view controller (VC for short) has the protocol SendMailDelegate is going to be the mail sender - in our case, SendMailVC. This means that SendMail has to also supply an envelope (a delegate) and the mail contents it wants to send. The receiver - ReceiveMailVC.swift - will need to define the function getMailDetails, and do something with the received mailToReceive.

Note that this mailToReceive object is a custom (Cocoa Class) Mail class object - one that I don't provide details for. This Mail object can do whatever you want it to do, so long as you define its properties; it can hold String content, a generic object, etc..

 

Now we can do a few different things:

• Conform to the protocol (create a delegation) in the .swift file that will be  receiving mail - in other words, our ReceiveMailVC.swift will be the recipient and should implement the getMailDetails function

• Implement the sending function in SendMailVC, so that we can send mail to the recipient (ReceiveMailVC)

• Create a delegate that will link to the delegation (in ReceiveMail), and allow SendMail to send mail

 

In order to do any sending, we first need the envelope - the delegate! Let's make one:

 ESCAPE='HTML'

Notice that I have to unwrap SendMailDelegate. I'll leave it to you to figure out why that's necessary (Xcode will tell you anyway).

Now that we have our envelope that we can send mail with, let's implement the sending function next - this will still be in SendMail:

 ESCAPE='HTML'

The only thing we're missing now is receiving mail from SendMail. Here's a way:

 ESCAPE='HTML'

This is the only function in ReceiveMail that has to do with the sending/receiving mail protocol example - the rest is mainly done in SendMail. This is also what I mean when I say that delegations can "transcend" the scope of their own file, because it is their delegate (in the scope of another file) that is doing the work of passing info to them from other files.

 

To recap on what we've done, here is what's in SendMailViewController.swift:

• the protocol SendMailDelegate, which contains the necessary delegations to define: getMailDetails

• the delegate envelope, which will carry out actions for the protocol in its delegation's honor

• the function sendMailDetails, which is not related to the protocol or delegates scene, but is a necessary function that will make use of the delegate, so that the delegate envelope can invoke its delegation getMailDetails

And here is what we have in ReceiveMailViewController.swift:

• the delegation getMailDetails, which conformed to the protocol SendMailDelegate in SendMail, because ReceiveMail is the one that wants mail info that is created in SendMail

 

We finally fully implemented a way to send and receive mail using protocols and delegates. Hope this helped!

 

Storing Data - User Defaults and Core Data

When storing information, Swift provides you with two tools: User Defaults, and Core Data. These tools are useful for when you want to save information that persists through launches of the app (such as settings or interactive options that the user adds/removes). The difference when choosing which one to use is size.

User Defaults: useful for when you want to store small or few things. A good example is if an app has settings options that need to persist through each instance of the app. Or, if there's an app that has bookmarking options, you can save the name of the bookmarked object.

Core Data: when you want to store big or lots of things. "Big" or "lots" generally mean if you have to populate the app with information. Do you have a library of some form that needs to be saved? A big list of Dictionary objects? Anything else that may grow in size?

If you're thinking of creating an app where each user has their own unique list of information (such as the friends they add/block, the events they sign up for, the comments they post/like), it would be better to use Core Data instead.

 

CORE DATA: RECOMMENDATIONS

The neat thing about Core Data is that because its function is more popular due to the sheer amount of persistent stuff an app has to save, there are quite a few server-side frameworks and libraries that allow you to store data locally on the individual device and backup to a server. One such framework is RestKit.

 

Multithreading

In Swift, multithreading can most commonly be handled by a framework called the  dispatch framework, or: Grand Central Dispatch (GCD). GCD takes some time to learn, but is a solid go-to when you want to implement a multithreaded system.

A quick recap or summary of threads, if you need it:

• A thread can be seen as a "piece" of a process or could be the whole process, where a process is a part of the end-goal program that needs to be executed. 

• Depending on how an OS is designed, threads can be ordered and executed in different ways: concurrently (seen in foreground and background processes), one after the other, back-and-forth, etc..

• For example, say you have two things running on your computer (abstract-wise): a video stream, and a download. The OS has to decide how to run these two programs so that activity seems seamless; it might be streaming a little bit of the video, and then jumping back to the download, and so on. Of course, it's more in-depth and low-level than that (if you've taken/are taking CS 429 and 439), and things like network interactions (such as buffering) exist.

 

You may not be using multithreading in the homeworks very much, if at all. But in your project, it's something important to consider implementing for performance purposes. For instance, if you have an app that needs to call and populate from an API, but that API database is pretty large (as in, it'd take more than a few seconds to pull from), you may want to consider having the population happen in the background.

Multithreading is very useful to implement, especially when you need multiple things done in relatively the same instance. Anything that doesn't need to show up or happen immediately but will need to when you visit that window, multithreading can eliminate the "loading time" by turning it into "pre- loading".

 

MULTITHREADING: RECOMMENDATIONS

Lecture covers GCD in concept, but here are a few good places to look if you want code:

• raywenderlich: Part 1 and Part 2

• Learn: Swift Multithreading Lab

 

Key-Value Observing (KVO)

Key-value Observing is an implementation that should be familiar to you if you come from Objective-C (given Swift's nature). The basis for KVO is to update related or reliant functions if an object happens to change (such as if an app is using a timer widget, and other functions of the app rely on that timer). By definition:

Key-value Observing is a mechanism that allows objects to be notified of changes to specified properties of other objects. You can use key-value observing with a Swift class, as long as the class inherits from the NSObject class. 

 

KVO: RECOMMENDATIONS

• The Developer's Guide provides you with 3 steps to implement KVO, with accompanying code. (You'll have to scroll down a bit, it's in the center of the page.)

• Additionally, another guide provides the structure of KVO, with pictures.

• Swifter: KVO

• Cocoacasts: Key-Value Observing (KVO) and Swift 3

 

That does it for not as basic functions and features of Swift and Xcode! I hope this helped, and if you'd like to glance through a list of compiled neat things to use for projects, the Extras is there for you.