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)

Basic

Here we go over basics in Xcode's Swift and the Storyboard. Much of it is explained in class or is simple to look up, but it's here anyway. The Swift Developer's Guide is a good reference for anything Swift.

 

Swift vs. Other Languages

Things in Swift that you don't need to do or worry about:

No semicolons: You don't need them! You don't. Don't finish the ends of statements with semicolons, or Xcode will complain.

No header files: You don't need these either. These are commonly used in C languages, but in Swift, the only "headers" you will have are importing modules that you need (ex: UIKit, CoreData, etc.).

No "break" in switch statements: If you want to use the switch statement, you don't need to use break after each  case. However, the very last case must be followed by a default case - what happens when none of the cases are satisfied.

No pointers: Unlike in C languages, Swift is memory-safe; you don't need to (or more like, can't) explicitly differentiate between non-pointer and pointer references. If you would like to work with pointers, however, there are modules and class types that allow you to do so (Unsafe Swift).

 

Things that Swift features:

Type inference: Swift will infer the type of a variable you are using - unless you are using a custom type or class, in which you will need to specifically use typing. No need to always explicitly say things like "var x: Int = 9"; the Int is inferred, and you can say "var x = 9" instead.

Strong typing: Swift will not let you get away with using the wrong typed variable. For example, if you try to input an Int into a function that requires a String as input, Swift will check for this during compiling and Xcode will complain before it even executes the program. This includes specifics with numbers: if a function is expecting a Float and you input an Int, Xcode will give you a warning.

Operator overloading: You can overload operators. This may be useful when you want to apply operations to the types you have defined, or define your own operators within a class.

Automatic management of memory: Just like Swift is a safe language that doesn't use pointers, it automatically manages memory - no need to clean up memory or worry about strange "things that shouldn't exist in space but exist anyway, how do I remove it".

Tuples/multiple return values from functions: Swift can return multiple values from functions, which is different from the typical "return one" that most languages employ. For example, if you want a function to return two Strings for first and last name, you could say:

 ESCAPE='HTML'

You can input first and last in multiple ways, for example:

 ESCAPE='HTML'

Version 1 will print: ("help", "me"), and version 2 will print: ("just", "kidding"). The output format is the same, but the input format doesn't have to be. Either way, the output is a tuple (a,b) as we wanted from the function name.

Generics: You can use generics!! In Swift, you can still use generic types such as <T>. You can extend them, constrain them, etc.. I won't go into everything, but you can always check the Swift Developer's Documentation (they give lots of examples for everything you can do).

AND FINALLY:

Optional variables: Optionals are a little... tricky? confusing? strange? to explain. By definition, the Swift Dev's Guide says:

Optionals are indicated by using a (?) symbol after a variable's name or type, such as:

var a:String?

a?.uppercaseString

In a sense, making a variable optional means you aren't yet sure exactly what the variable is going to be initialized to, so for the time being it's nil - the actual value will be given to it later, just not during initialization. Using the first example, saying var a:String?  says that you know that a is going to be a String variable, but haven't initialized it to a value yet (because if you did initialize it immediately without making it optional, you would say something like var a:String = "hi" or something).

To note additionally, optionals return differently from normal values:

var a:String? = "hi"                  // returns Optional("hi")

var c:Int? = 3                  //returns Optional(3) 

Only by unwrapping an optional by using the (!) symbol will you get the actual value associated with it. Using the above examples:

var a:String? = "hi"                  // return(a) gives Optional("hi")

print a!                  // return(a!) gives hi

Here, a is first initialized as an Optional, with the String value "hi". If we returned a directly using return(a), we would get the value  Optional("hi"). However, the next line unwraps a via a!, and instead of Optional("hi") we get just the String output  hi.

You can play around with optionals further in the playground or in your homeworks. Optionals will be especially important in your later homeworks, when you'll be using custom-made classes and assigning optional values (ex: if you have a Candidate object, you might not know exactly what value/person the  Candidate is, only that you'll give it the value later, so you make it optional for now). Don't forget to unwrap!

(In other words, if that still didn't really help you, you may be using both ? and ! until Xcode stops complaining. It starts to make sense once you realize the exact state and value a variable is in at the time of use.)

 

Language Basics

Logic

As expected, Swift supports the general operators and logical operations that most other common languages also support.

Basic operators: =, +, -, *, /, % (remainder aka modulo in most languages). It's important to note that % works like mod, unless we are working with negative numbers. So technically, (%) in Swift is not modulo (which always returns positive), but purely remainder (which can return negative values). 

Comparison operators: ==, !=, >=, >, <=, <. These work as you would think they do.

The "shortcut" if statement operator: A ? B : C. How you read this: "if A is true then B, else C."

The nil-coalescing operator: a ?? b. How this works is that Swift will unwrap  a and return it if it's not nil. But if a is  nil, then it returns b instead. a must be an optional-type variable, and b has to be the same type as (since this is a comparison, and we compare between like types).

Interval operators: a...b, a..<b. a...b goes from to  b, including b. The interval a..<b goes from up to b, therefore not including b.

• Boolean operators and logic: !, &&, ||. These remain the same; ! for NOT, && for AND, and || for OR. There are no operators for the compound logics, like XOR.

 

Looping

Looooooops. The first thing that comes to mind for me is a for loop. Let's see a simple example:

 ESCAPE='HTML'

Simple loop, right? However, this format of looping is not supported by Swift - in fact, Xcode will throw you a warning when it sees something like this, and lets you know that this is an out of date style. Let's try something like this instead:

 ESCAPE='HTML'

This works! This for loop - technically and officially called a for in loop -  will do the exact same thing as the first format - print the numbers 1 to 20 - but this is the style that Swift uses and Xcode approves of.

Of course, for loops are not exclusive to just integers. We can loop through arrays of any type, such as Strings, or a custom type . For loops are also not the only type - there's still the while loop, and also the repeat-while loop, which is a variation of the while loop.

• while - evaluates conditions at the start of the loop

• repeat-while - evaluates conditions at the end of the loop; similar to do-while loops in other languages

 

Conditionals

Conditional statements are any kind of statement that puts a "check and fulfillment" condition. Most notably is the if statement, but Swift gives you both the if and  switch statements to work with for conditionals.

 if - if the condition is met, perform the following. If not, move on. if statements in Swift also use else if and  else - an if statement must end with an  else statement (Xcode will warn you otherwise), but you only need to use else if when you have more than 2 conditions.

• switch - there are multiple patterns that can be checked at the same time. If the condition of any of these blocks is met, perform the actions in that switch block. If not,  default to the base case. As mentioned before, switch statements don't require using break after each case. It's important to mention, however, that the command break is and can be used as a general command, so you technically  can use break after each case, if that is what you want your  switch statement to do.

Here is a good general layout for a switch statement, given by the Developer's Guide:

 ESCAPE='HTML'

That does it for the basics of the Swift language itself. In the next section, we'll go over how to setup for playgrounds and projects!