Skip to content

Files

Latest commit

author
Jake Brabec
Aug 24, 2017
2a2985e · Aug 24, 2017

History

History
286 lines (149 loc) · 14.4 KB

swift.md

File metadata and controls

286 lines (149 loc) · 14.4 KB

Introduction to Swift (Part Two)

Simple Data Structures

When working on our ground-breaking applications there will come a time for us to be able to store data. This data maybe range from user’s name to the items they currently wish to purchase in your ecommerce application.

Int and Double

In order to store numbers, we to use a data type called Int

The data type Int stands for Integer which hold whole numbers.

If you wish to save a decimal number, then we will need to use a data type like Double.

Double stands for double precision floating point which essentially is just real numbers

So the number of people in a room would be an Int since we can’t have half a person.

While the price of lunch will be a Double since we calculate food prices till the nearest hundredth.

String

It’s very common for you as a swift programmer to store your users name. Or if you’re working on a social networking application then you will need to be able to store the messages. Another time when you may need to use string is when you may need to show the items in your apps catalog.

Unfortunately, neither can hold words. For swift to store words for us we need to use the data type String.

String are typed in around quotations so an example of a string literate, meaning it was entered by the programmer as opposed to taken in by the user of your application would be:

"Hello, this is a string."

BOOL

Bool's come in handy when you’re living in a world without maybe's.'

If you’re trying to present a situation to your user where there are only two options then you use Bool.

An example of this would be your enrolment in Purdue University. You are either a student enrolled at Purdue University or you aren't.

Its either a yes or a no

True or false 1 or 0

Swift deals with Bool as either having a value of true or false. For example, a user can be following you or he/she cannot. If they are following you then the following condition is true else false.

Constants, Variables, Functions

Like C, Swift uses variables to store and refer to values by an identifying name. Swift also makes extensive use of variables whose values cannot be changed. These are known as constants, and are much more powerful than constants in C.

  • Excerpts From: Apple Inc. “The Swift Programming Language.” iBooks.

Thanks Apple 😒... Now let’s put it in terms we can actually understand.

Variables

A variable is essentially any data that you want to store and is expected to change. What do I mean by that. Think of the temperature in a room. The room temperature is always as flux, its always changing. As the brilliant swift programmers we know we are, we know that in our temperature application, the current room temperature is always changing.

Similarly, the current speed of your car should also be treated as a variable, it’s always changing. Except for when its parked but even then, it’s probably not going to stay that way.

Now, we need a way to actually 'refer' to these values, that’s where variable names come into play.

Going back to our temperature example,

We need to have a way to keep track of the varying temperature in case we want to use it to tell the air/air conditioning to turn on. Let’s see how we would refer to our current room temperature

In order to tell swift that something is a variable, we need to use the swift keyword var. Let’s make a variable to refer our current temperature using the var keyword.

var currentTemperature

Now swift, needs to know the type of this variable. We know that the temperature will be a Double, but sadly swift doesn’t. To state the type of a variable. We declare the variable current temperature, which represents the current temperature of the room in the following manner:

var currentTemperature: Double

Now swift needs an initial value to allow us to use our variable, currentTemperature. Considering that all thermometers start off with an initial value of 0. To give currentTemperature an initial value of zero, we will do the following in swift.

Declaration and Initialization:

var currenttemperature: Double = 0

var/let variable name: Type = Initial Value

And we have successfully initialized currentTemperature to a value of zero and now we can use it and change it to whatever we want.

Similarly, to represent our car's current speed we would declare and initialize it in the following manner:

var currentSpeed: Int = 0

We used Int here since it’s rare for a cars speedometer to be accurate to a tenth of a place.

A variable to indicate whether a user is following another user would look like the following. Note we used BOOL here cause a user can only be following on not following a user.

var isFollowing:Bool = true

Constants

Constants are variables that cannot change their values. An example of that would be the location of Purdue. Now the number of students attending Purdue is always changing but its location is always the same. But when working with both in an application that provides you with information about Purdue we will be needing both.

Declaring a constant:

let purduesLocation: String = "610 Purdue Mall, West Lafayette, IN 47907"

Declaring a variable:

var numberOfStudentsAtPurdue: Int = 40451 Now let’s say that the Class of 2017 graduates, the number of students at Purdue would decrease. Let’s say it becomes 40,000. We would tell this to swift in the following manner:

numberOfStudentsAtPurdue = 40000

We were able to change the numberOfStudentsAtPurdue because it is a constant, we can’t do the same with a constant. We can’t change the value of purduesLocation.

purduesLocation: String = "Location – Khalid” - we can't do this, swift will throw an error at us stating that we are trying to change the value of a constant declared by the keyword let. It will suggest that we can change the constant that we are trying to change to variable. let -> var

Note!!! You don’t need to initialize a constant by a literal value (entered by you in code), it can be initialized by the value of another variable/constant.

To sum it up:

let is constant

var is dynamic

Functions

Functions are self-contained chunks of code that perform a specific task. You give a function a name that identifies what it does, and this name is used to “call” the function to perform its task when needed.

  • Excerpts From: Apple Inc. “The Swift Programming Language.” iBooks.

Let’s consider our bodily functions for a second before we continue.

Our body constantly does a couple of actions constantly such as respiring, walking and sleeping. If we were to implement our body's functionality in swift then we would have to type in the code for sleeping, walking and respiring every time we would want to state that our body would do those actions. It makes more sense for us to have a way to the instructions for these actions stored someplace and only defined once and then simply access them when needed.

This is where functions come into play, they’re pieces of code that we define once and only call when needed. This prevents us from calling the code constantly.

A function like a variable needs a name to be identified by. A function also needs to state what it returns in case it does some computation or retrieve some data for us.

A function may also take in some data in the form of arguments. An example of this would be coding out eat for your body, you would have to pass in food to the eat function for it to be consumed by you in our human model.

Lets write out the function schematic for eat:

func eat(food: Food) -> Void {
	body
	.
	.
	.
	return Void
}

A general definition of a function would be:

func FunctionName (FirstParametersName: Type, SecondParametersName: Type ...) -> Return Type {
	body
}

where,

  • func is a swift keyword that tells swift that you are going to begin defining your function, that is stating what your function does.
  • function name is what you will use to call a function
  • FirstParameter, SecondParameter: is what is passed into the function. This may be data that the function will use to do or compute something or gain access to other data like the food passed in to our eat function
  • return indicates that the function has reached a point where it has reached a viable result and could be what the function caller wanted.
  • If a function retrieves something for you or computes a value then it will probably have a value. If a function does not need to return a value, then it returns void or nothing.
  • Your functions body is where you tell your function what to do

Now that we know how to define a function, let’s see how to call one. To call a function all you do is simply type its name and pass in any necessary arguments. If a function takes in no arguments then you pass in none in the function call.

An example of this would be a function for waking up:

wakeUp()

while a function call that does take parameters woud look like our eat function:

eat(food)

To generalize function calls:

functionName(parameters) where parameters may be zero or more

Arrays

Think of Arrays as a list of similar items.

Let’s think about a To-do list. Every item on the list is something that is yet to be done. These items on the list are of the same time. We can say that our array is an array of type To-do Items. Similarly, when we store a bunch of numbers in the form of a table or list then we would user Double or Int depending on whether we are using real or whole numbers respectively.

Arrays in swift are written as: [Data Type]

var stringArray: [String] = [String]()

To add an item to an array we use the append(newitem) function of the array type:

Let’s say we had an array of names of participants at a contest an a new participant enters the competition. This is how we would append (adding a name to the end of the array) it. Note: this is being done assuming that we already initialized array called participants of type string = participants: [String] was initialized already. let newParticipantsName = "Geo Philippa" participants.append(newParticipantsName) To get the number of items in an array we simply access the count attribute of the array. To get the number of participants in our array we would simply access it in the following manner:

participants.count // gives the number of participants in participants array

Optionals

Optionals are a key component of programming in swift. But before we go on and actually define what optionals in swift are let’s talk about the average shopper at a clothing store. Let’s say that each shopper would have a cart as they enter and checkout the items in the cart when they leave. Now there is no guarantee that every shopper will have something in their cart. In this case the value of that shoppers cart will be nil and so it will NOT HAVE A VALUE.

If a shopper does like one or more items in the store and wish to purchase it, they would put it in their cart to checkout. In this case when checking out and returning the cart, their cart will not be empty and will have clothing items. You can say that the shoppers cart will will have a value.

A good way of representing the item in a store is through their item ID's. We know that since we aren’t going to do any arithmetic on our id's its best to treat them as strings.

So to represent the cart, we are going to use an optional array of type string

In swift to state that any variable is an optional we use ?

An optional integer would be declared in the following manner:

var optoinalInt: Int?

The following is how we are going to declare and initialize this array:

var shoppingCartArray: [String]? 

If an optional is not initialized, swift sets its value to nil

then when set swift tries to access that value if found.

To give our shoppingCartArray a value let’s say we held all the objects that the user selected items array: itemsSelectedArray

shoppingCartArray = itemsSelectedArray

Now if we were to get the count of shoppingCartArray it would be an optional 4 since its value originates from an optional but it would be a value.

If we are to ever retrieve the value from an optional, it would be wrapped, meaning that it would be presented as Optional(value). In order to remove this we need to remove unwrap the value. There are various ways of unwrapping an optional. Some of which are:

  • Force Unwrapping

In order to unwrap an optional all you have to do is add a ! at the end. So in order to unwrap an optional such as our shoppingCartArray we can simply force unwrap it in the following way

	print(shoppingCartArray!)

	This will print out all the contents of the array separated by commas without being surround by an Optional() wrapping

It may be a good idea to check using an if statement if the optional contains a value or does not contain nil before unwrapping it else swift will try to read it and crash our application. This is how we would go on about it

	if shoppingCartArray != nil {
		print(shoppingCartArray!)
	} else {
		print("Your array is nil")
	}
  • Optional Binding

Optional Binding is the most common method of unwrapping an optional. Optional Binding is similar to forcefully unwrapping an optional after checking if it contains a value or is not nil. But instead of unwrapping it we tell swift through a special if statement to assign it to a variable

We use the if let syntax to assign the value of an optional variable to a constant to be used.

	if let unwrappedshoppingCartArray = shoppingCartArray {
		print(unwrappedshoppingCartArray )
	} else {
		print("Your array is nil")
	}

Both have the same result, only Optional Binding gives you a variable to use whereas forcefully unwrapping optional after a value check through an if statement only notifies you that your optional has a value.

A good way to look at optionals is think of anything that is an optional to be stored in a box with a hole at the top. When you simply force unwrap an optional value you simply are tipping the box over and seeing if something falls out, if it does then your box had a value and you’re good else swift is going to crash cause it just read in nothing of value and does not know what to do now.

When we use optional binding, or check for a value before unwrapping an optional we simply shake the box to hear for something in the box and if we do hear something then we turn it over. We then get the value and carry on from then on out.