Swift Pair Programming – Session 5

screenshot-from-2016-11-10-100142Yesterday, Nick and I pair programmed Swift in Screenhero. We’ve been doing sorting algorithms over the past few weeks. This time we discussed changing up the game plan.

During our previous pairing sessions we created a playground in a swift ios project. Apparently, creating a playground in a project prevents you from getting real-time compilation and console output.

Another reason for working with Swift in a project, rather that just a playground, is that we’ll be able to utilize some of the libraries and frameworks that are available in a full project. To be honest, I’m not sure how to import a library or framework into a Swift playground.

Therefore, after listing these concerns with Nick, we decided to pair program within the confines of a project. In the past, Nick mentioned wanting to do some image manipulation. I’m most interested in setting up a single point of authentication with OAuth.

Combining these two desires together, we decided to code up an Instagram clone for our pairing sessions.

Last night we found p2/OAuth2, an open source OAuth project on github, that is written in Swift (our pairing language). I was about to clone the repo and import the contents into our project when Nick showed me some awesome new technology called CocoaPods.

Before I talk about CocoaPods, let me explain about package managers. Package managers are like magically updating software managers that pull the latest updates from an internet connected manager and bring all the files, dependencies, and configurations into computer automagically. All the computer scientists just cringed a little from my explanation. That’s fine. It works for me.

Usually these package managers, like homebrew, npm, and apt are used to update the packages on your computer. With CocoaPods the community has brought together a package manager for iOS applications!

We created a pod to download p2/Oauth2 and spent the rest of the pairing session configuring the pod and attempting to connect to Twitter’s API to get a list of Nick’s Twitter followers.

We didn’t manage to get the authentication working last night. Next week we’ll get the application to authenticate. Then I’d like to work on integrating Facebook. Then IG, if that’s possible.

This week, to prepare for our next programming session, I’ll be testing out the p2/OAuth2 code from my personal machine at home. And I’ll also be doing Ray’s tutorial on OAuth2 in Swift. Nothing like being prepared, setting an agenda, and checking off items on a list ūüôā


Swift Pair Programming – Session 4

Today Nick and I worked on the insertion sort in swift. The biggest problem we ran into was learning how to iterate through an array in swift backward. We ended up using “stride” to define the start, end, and increment amount.

Here’s the code for stride:

for index in stride(from: 5, to: 1, by: -1) {

There is also a way to do this in swift using the reverse function:

// Print 10 through 1
for i in reverse(1...10) {

Next week we’ll be tackling the merge sort.

Swift Pair Programming – Session 1

Just finished pair programming with Nick. He’s in San Francisco. And I’m in Hawaii. We’re using ScreenHero to pair and it’s fantastic. There was a bit of a lag in screensharing because my internet connection was pretty bad. Next time I’ll be pairing from the library or from Hi Capacity. An hour goes by really quickly. Maybe we need to meet for longer?

Prior to meeting I made a list of the topics that I understand the least:

  • Closures
  • Coalescing operators
  • Optional binding
  • Force unwrapping
  • Guard statements
  • Optional chaining
  • veratic parameters
  • inout parameters
  • Nested function that returns a function
  • Currying

Questions that came up this session

How to we indicate a multi type array?

Lessons learned

  • Playground will not show up the play button if its a playground inside of the xcode project.
  • edit all in scope.
  • can’t do ++ in swift
  • Figure out how to do a next item in swift that is safe
  • Use inout in your parameter list to mutate parameter. Be sure to call method with & on parameter to indicate inout status

Shared tools:

SpectacleApp – FREE mac app to move and resize windows with ease. Window control with simple and customizable keyboard shortcuts. For mac.

Next Week:

We’re planning on finishing the bubble sort.

Swift Pair Programming – Session 3

Playground supports markup
  //: Playground - noun: a place where people can play

import AppKit for osx
import UIKit for ios

source files in sources folder will be compiled once
image files in resources file will make those resources available to your playground

each page has its own sources and resources files

previous and next links allows us to go back and forth between pages

markup allows us to create links between pages.

semicolons are optional in swift.
  do not put them into the code.
  only time to use is when you have two statements on a single line

0..<64 means 0 to 64

NSLog still works. Good to use if you want a timestamp in your console

veratic function can take multiple parameters

print() default separator and terminator can be found in function definition

show graph of function by clicking on Show Result button in the result side bar

"//TODO:" inserts a bolded label in the jump bar


func printLiteralExpressions() {

	print("Function: \(__FUNCTION__)")
	print("Function: \(__FILE__)")
	print("Function: \(__LINE__)")
	print("Function: \(__COLUMN__)")
  Function: printLiteralExpresions()\n // name of this function
  File<EXPR>\n // does not work in named playground file but works in all source files
  Line7\n // line in source file
  Column:20\n // column in source file

Literal expressions are preceeded and succeeded by __ (2 underscores)


Create landmarks in swift playgrounds with the following one line comments:

// MARK: This is viewable in the jump bar
// MARK: - Add separator above this line
// TODO: Do this
// FIXME: Fix this

MARKUP: (make sure "render demarcation" is enabled in the right gutter )

## Header
### Header
> Block quote
* list item 1
* list item 2
1. List item 1
2. List item 2
`code format`
quick help comments
/// A quick help comment
Quick help multiline comment
- seealso: `someComplexFunction` // allows to embed link to function in playground


type swift in command line
press return
use up and down to shuffle through history
#> means waiting for input
#. means waiting for more input
Press tab for autocompletion in terminal
:q to quit
REPL can be started in the middle of a paused xcode app
  just type repl in console


use . notation to access property of class
use same . notation to set the property of a class
can chain multi dot notation
Good to cut up long dot notation like so:
  .print() // works because when compiler encounters . on line, looks for line above for reference


Swift has 2 types of values
  Value types (passed by copy)
	    Floating points
	    Tuples // forgetting what these are
	    Optionals // any datatype may have a value or be nil
  Reference types (passed by reference)
    **Closures // really want to focus on closures

Value types are passed by copy
  passed to a function
  changes to copy will not affect original
  value types are not copied until they are changed (implementation detail)
Reference types are passed by reference
  Uses a pointer to a reference
  Both pointing to the same exact instance

Variables are mutable (var)
Constants are immutable and cannot be changed (let)

Always create as constant if you don't need to change it later

Swift is a strongly typed language
Compiler will infer type of instance based on what is being assigned to it.

All types in swift should begin with capital
Variables and constants should begin wtih lowercase letter
Camel casing should be used to distinguish multiword types and instance names
Variable names and characters can be used with unicode and emojis!

Equivalent ways to explicitly state what kind of data type it is:

let aCharacter : Character = "a"
let bCharacter = "b" as Character // as operator literally casts the previous character

Write unicode scalars with \u <unicode value>
  let uWithUmlaut: Character = "\u{75}\u{308}"

When defining ints, use underscores to denote placement for easy reading
  1000000 can be written as 1_000_000
When writing an unsigned int:
  let anUnsignedInteger : UInt = 1_234_567

Float - 6 decimal precision
Double - 15 decimal place precision
  Use Double as default is recommendation from apple

Booleans are defined with true and false
  explicitly define your bools with let bool : Boolean = true


let binaryTen = 0b1010 // 0b
let octalTen = 0o12 // 0o
let hexTen = 0xA // 0x
let twelveMillion = 1.2e7 // 1.2 * 10^7

DEFINING TYPE ALIASES // option click to see what type it is aliasing

typealias IPOctet = UInt8 // use alias to lessen typing
  alias keyword followed by original word
let minOctetValue = IPOctet.min
let maxOctetValue = IPOctet.max

Type must be explictly declared when a value is not assigned on declaration

Constants accessed before defining value, will error.

Optionals allow us to declare
  suffix with a ?
    contains some value or nil
    nil is a valueless state
    empty string is not same as nil

Optional type is a box
  access a value we know has a string, must unwrap it.
  force unwrapping is used by following optional with !
  keeps your code as safe as possible.
  run time error will be cause if it is used unwrapped

String instances are passed by copy

M_PI is a constant imported in Foundation

print(String(format:"The %@ with a radius of %.0f", shape, radius))

String manipulation:

let quote : String = "In the end, we only regret the chnages we didn't take."
quote.hasPrefix("In the end") // true
quote.hasSuffix("Abraham Lincon") // false

let firstCharacter = quote[quote.startIndex] // gets substring

let eigthCharacter = quote[7] // does not work, will not accept int as index here
let eigthIndex = quote.startIndex.advancedBy(7) // use advancedBy method to get index
let eightCharacter = quote[eightIndex]
let lastCharacter = quote[quote.endIndex.predecessor()] // gets the eigth index

Insert and delete string componenets:

quote.insert("!", atIndex: quote.endIndex.predecessor()) // insert character at end of string
let period = quote.removeAtIndex(quote.endIndex.predecessor()) // returns last character in string

Create range:

To and including last number
  let aRange = 1...3
  let startIndex = quote.endIndex.advanceBy(-41)
  let range = startIndex..<quote.endIndex // creates range start to last number inclusive
  quote.replaceRange(range, with: replacementString)

Escape Characters:

\n - new line
\t - tab
\ - escape \ and "
\0 - null character

Swift has 3 formal collection types:

Default initializer:
var testScores = [Double]()
var testScores2 = Array<Double>()

Set array with multiple values at once
var scores = [Double](count: 4, repeatedValue: 10.0)
var scores2 = Array(count: 20, repeatedValue: 0) // element types infered by repeated value

Can be inialized wtih optionals
Pick a style that works for you and stick with it.

threeStooges.isEmpty // checks if has any elements
threeStooges.contains("Moe") // returns true or false

let twoStooges = threeStooger[0..<2].sort(>) // sorts array in ascending order

Arrays passed by copy

Use + to join 2 arrays.

myArray + ["David", "Shemp"]

// Nesting arrays

Break them into separate lines to make it look good.

print(famousGroupsOfThree.flatMap( { $0 } )) // flaten multidimensional arrays
// this is a closure function
// short hand argumenting

Store values of the same type in Dictionaries.
No redundant keys are allowed.

Declare Dictionary

var birthYears : [String : Int] = [:]
var raceResults = Dictionary<Int, String>()
var tourDeFranceResults : [Int:String]

Setting a value to nil removes it from the dictionary

Get all values in array


Modifying Dictionaries

Remove value for key returns key

You can nest dictionaries as well

Optional chaining
If any part is nil along the way to resolving the value, return nil.

Sets have a long form

var teachers = Set<String>()
var staff : Set<String> = []

When adding items to a set, any dupblicates will be removed.

Set supports count and isEmpty


Insert and remove values in Sets

Need to force unwrap arguments if the method does not accept an optional.

Defining Tuples

Group multiple values into a combinatorial value.

Useful to return multiple values from a function.

let httpStatus = (200, "Ok")

var playerScores: ([Int], firstName: String, lastName: String?)

Tuples can be accessed by index or by the name of the variable

**Tuples seem like a light-weight class replacement.

Add up the scores in tuples liek this:
let averageScore = scores.reduce(0, combine: +) / scores.count

Writing underscores for unneeded values can speed up compile time.

let (httpStatusCode, _) = httpStatus200

** use the letter t to switch lynda.com viewer from fullscreen to normal

Use dot notation to access nested tuples.

// Operators

Compiler will change int values to float implicitly

Division of integers will return an integer. Change one of those to a double and it will give you a decimal.

Swift modulus does floating point modulus as well!

a &+ 1
wraps around to maximum value.

Strings can use + and += to concatenate string

Arrays can use + and += to join two arrays

Instances of a class are passed by reference.

== checks for equality between operands
**=== checks if two operands are pointing to the exact same instance

Supports ternary operators ? true : false

Ternary operators can be nested like so:

let generation = birthYear < 1945 ? "Greatest Generation" : // switch statement is better than this
birthYear < 1965 ? "Baby Boomers" :
birthYear < 1982 ? "Generation X" :
birthYear < 1965 ? "Generation Y" :
"Generation Z"

**Coalescing operators
let defaultSize = "M"
var selectedSize: String?
let orderSize = selectedSize ?? defaultSize // not sure I get this one

Range operators

to but not including the ending value

let rangeA = 0..<10 // 0 through 9
let rangeB = 0...10 // equals 0 through 10 including 10

Type checking and casting operators:

Classes are reference types

class ClassB : ClassA // Class b inherits from Class A

let arrayOfClassInstances = [a, b]

item2 is ClassB // checks to see if this is an instance of the ClassB class type

// as! is a forced downcast
let classBInstance = item2 as! ClassB

// as casts a subclass as its superclass

let classBACtingAsClassAInstance = classBInstance as ClassA

[AnyObject]  // allows for any kind of class in the array
[Any] // allows for any kind of class or value in the array

Preceding zeros can be removed in a 0b00001010 binary value
rewrite as 0b1010

For loops do not need to be wrapped in paranthesis

for i in 0..<10 {

for _ in 0..<3 {  // underscore used here when the variable i is not needed.
print("I will not waste chalk")

// Stride method allows us to iterate through a loop at different step lengths between

for i in 3.stride(to: 30, by: 3) {

// print out key value pairs in an array

for (k, v) in people {
print("\(k): \(v)")

// iterat through values in a Set
for v in letters {

// iterate through array with conditional
for n in numbers where n.isPrime {
print("\(n) is a prime number")

//While loops

click blue play button in playground to re-execute the playground code

if statements don't need parenthesis

// if available

if #available(iOS 9, OSX 10.11, watchOS 2.0, *) { // stars indicate a wildcard. Parens required for #available()

    // Use applicable API from iOS 9, OS X
} else {
    // execute other API code if those platforms are not available

**// Optional binding

var firstName: String? = "Betty"
if let firstName = firstName { // set as constant

**// Guard statement

guard birthday.earlierDate(twentyOnesBirthday) == birthday
  else { // falls through if false
    print("\(name) is not old enough")

  print("\(name) can enter")

values assigned in a guard statement endure for the lenght of the guard statement.

// Switch

// create switch based on 2 values

let die1 = [1, 2, 3, 4, 5, 6].randomItem()
let die2 = [1, 2, 3, 4, 5, 6].randomItem()

switch(die1, die2) {
    case (1,1):
    case (6,6):
      print("30 points")

// Using Labels // NEVER GOING TO USE THIS!!!

var i = 0
let hello = "Hello, Playground!"

start: do { // here is the label
  do {
  if i < 3 {     continue start // goto label   } } // Enums Use dot notation to write out the enumeration quickly // Defering code execution if allSystemGO {     defer { // runs only after the for loop completes and reaches end of if scope       print("lift off!")     }     for i in (1...10).reverse() {       print(i, terminator: " ")     } } // Optional chaining **if let marciasAge = hank.children?.first?.children?[1]. // if anything along the way is nil, whole thing is nil //optional chain always returns an optional. func sayGreeting(greeting: String, toName name: String) { // sets name with directive toName:     print("\(greeting), \(name)!") } func addTwoIntegers(a: Int, _ b: Int) { //underscore suppresses the parameter name     print("\(a+b)") } addTwoIntegers(3,5) func addTwoIntegers(a: Int, _ b: Int) { //underscore suppresses the parameter name     return a + b } let sumOfIntegers = addTwoIntegers(3,5) // set a function name to be reused let integerAdder = addTwoIntegers // this sets the method to this new method name let integerAdder: (Int, Int) -> (Int) = addTwoIntegers


let helloWorldSayer: () -> () = sayHelloWorld // keep in mind to keep off parens for the method itself

Void is just a type alias for an empty tuple

so it can be rewritten like this:

let helloWorldSayer2: Void -> Void = sayHelloWorld

// set methods with default parameters like this, set default parameter at end of parameter list.

func sayGreeting(greeting: String, toName name: String = "friend") { // sets with default param
    print("\(greeting), \(name)!")

sayGreeting("Hey") // now we can omit the name because it has a default value set on it

**veriatic parameters

**inout parameters // pass values by reference

// prefix argument with & to show that it is an inout parameter and passes by reference

// Create contextual help

Mutates passed in score
- parameter score: raw score
- parameter meanScore: average score
- parameter deviation: standard deviation

@available(*, introduced=1.2, depreciated=2.0, message="Use different version") // used to depricate a function

// Pass reference type parameter to function

Pass a function into another function:

func addTwoIntegers(a: Int, _ b: Int) -> Int {
  return a+b

func performIntegerOperation(operation: (Int, Int) -> Int, a: Int, b: Int) -> Int {
    return operation(a, b)

// rewritten to take a function instead of parameters

performIntegerOperation(addTwoIntegers, a: 10, b: 8) // notice we do not pass the parens, we pass the function name followed by a list of parameters

**// create nested function that returns function
  // requires returning an alias of the function that is created inside of the nested function

**// Currying

replace multiparameter fucntion with a single curried function

func addLineItem(product: String, price: Double)(quantity: Int) -> String {
    let discountMultiplier: Double
    switch quantity {

    return String(format.....)
let sellCustomTShirt = addLineItem("Custom Tshirt", price: 10.0)
var lineItem = sellCustomTshirt(quantity: 5) // here is the result of currying the function, can call with default vars and a single param

**// Error Handling

Handling Errors

use enumerations for swift error handling.

define functions that throw errors

func performAction() throws {
  guard encounteredErrorA = false else {
    throw Error.A  // control will be moved out of the function
  guard encounteredErrorB = false else {
    throw Error.B(code: randomCode, function: __FUNCTION__.
      line: __LINE__)  // throws literal function name and line number
    print("Action completed successfully")

do {
    try performAction() // need to call with try to a func that throws
} catch Error.A {
    print("Error: \(error)") // local error value is created by a catch clause
} catch Error.B(code, function, line) where code > 4 {
    print("Error occured in \(function) at line \(line) code" \(code)") // local error value is created by a catch clause
} catch {
    print("Something went wrong: \(error)") // catch all statement here

Overloading Function // same name, different inputs
  can coexist when they have different parameters
  can coexist when they have return types parameters

Create custom operators
  Start wtih ascii characters or unicode calendars
  Must be declared globally

infix operator <==> { precendence 130 associativity left}

func <==> (left: CGPoint, right: CGPoint) -> Bool {
    return left.x == right.x && left.y == right.y

pointA <==> pointB

****Closures // supports so many varieties of a closure!

Functions in swift are actually a type of closure
  Can be coded inline, blocks, lambdas, or anonymous functions
var names = ["David", "Jenny", "Mock", "Pie"]
let sName = names.filter({ (name: String) -> Bool in
    return name.lowercaseString.characters.first! == "s"
let sName2 = names.filter {
    $0.lowercaseString.characters.first! == "s"
let reversedSortedName = names.sort { $0 > $1}

Swift Pair Programming – Session 2

Just finished doing the “Learn Swift 2 The basics” training on Lynda.com. Learning the language is pretty smooth with this tutorial. I’ll have to learn more are conditionals, unpacking, and bridging headers to combine Objective-C and Swift in the same project.

source: https://www.lynda.com/Swift-tutorials/Learn-Swift-2-Basics/437175-2.html

Questions for Pairing

  • Should we experiment in playgrounds?
  • Should we do the entire project?
  • Maybe start with basics in playground to get real time compilation

Swift Data Types

// let defines a constant that cannot be modified
// var defines a variable that is mutable
// swift compiler has inference
// write a = 5, compiler thinks it is an int
// explicit typing:
// var a : String = "text example"
// strings can be combined with +
// string interpolation, putting strings (or different data types) inside strings

var numDays = 5
let toPrint = "There are \(numDays) days in the weekend"

// arrays created like this
var myArray : [Int] = [3,5,7]
var myArray = [3,4,5]
var myArray2 : [Int] = Array() // needs explicit definition to add right type of data
var complexArray : [Any] = Array() // allows any kind of data type
complexArray.append(3) // adds int
complexArray.append("Hello World") // adds string

// dictionaries created like this:
var myDictionary = ["apple":"red", "banana":"yellow"]
var myDictionary : [String:Int] = Dictionary()
myDictionary2["apple"] = 0
myDictionary2["banana"] = 1

// **optionals are advanced and unique to swift
// situations where a variable might not have a value

var c : Int? // tells compiler c might be nil or might have a value
var d = c! + 5 // must address that optional c is force unwrapped, only do when sure variable has value
if let nonOptioonalValue = c { // optional binding, only do if has value
  var e = nonOptionalValue + 5 // not executed if c is nil
import Foundation
var optString : String?
// I know this might be nil but still try it
optionString?.stringByAppendingString("more"); // if optionString is nil, you will get nil back from operation

// operations require operands to be of the same type
// if different, cast to same type
// curly brackets are always necessary in conditional statements
// switch statement allows case elements to be strings.
// no need to add break keyword after each case
// breaks automatic
// fallthrough keyword allows to go to next case without breaking

// guard statements
guard(t < 0) else { //functions like an if valid
while loops
repeat {
  // runs once before the test
}while(i < 10)

// iterate through range of numbers
for index2 in 1...15 {
  index2 // increments itself from 1 to 15, prevents off by 1 errors

// iterate through array
let myArray = [1,5,10]
for a in myArray {
  a // prints out 1, 5 then 10


func sayHello(name: String) -> String { // says this function returns a String
  return "hello, \(name)" // example of string interpolation
func customGreeting(name: String, greeting: String) -> String {
  return "\(greeting), \(name)"
customGreeting("Bob", greeting: "Hi") // in swift common practice is to make first parameter not named, then rest are named

// force swift to disregard a named parameter
func sayHelloToFullName(firstName: String, _ lastName: String) -> String {
  return "Hello, \(firstName) \(lastName)"
sayHelloToFullName("Bob", "Smith") // does not require named parameter because of _ in function definition
strings get length


  • classes are good for inheritance
  • structs have a limitation, no inheritance and are passed by copy, not reference
  • enums can include functions

// simple class definition
class myClass {
  var a = 3
  func classMethod() -> String {
    return "Return Value"

var c1 =  myClass()
cl.a = 10

// simple class definition with initializer
class myClass {
  var a : Int
  init(initialValue: Int) { // constructor
    a = initialValue
  func classMethod() -> String {
    return "Return Value"

var c1 =  myClass(initialValue: 15)
cl.a // initialized with 15
cl.a = 10

// build struct
struct myStruct {
  var a = 4
  init(initialValue: Int) {
    a = initialValue
  func structMethod() -> String {
    return "Return Value"

var st = myStruct(initialValue: 12)
st.a = 16
st.structMethod() // all these are the same as class
<h4>// build enum</h4>
enum myEnum { // stores list of possible values
case Value1, Value2, Value3 // stores values with same keyword as switch
init() { // sets custom default initializer
  self = .Value2
// enums cannot store properties
static var testValues = ["Test1", "Test2", "Test3"]// can have static variables
func returnMyValueInStringForm() -> String { // can have functions in them
  switch(self) {
    case .Value1: // enumeration is equal to first value
      return myEnum.testValues[0]
      return myEnum.testValues[1]
    case .Value3
      return myEnum.testValues[2]

var en = myEnum.Value1
var en2 = myEnum // implicitly sets with default init method


class Employee {
  var yearsWorked : Double = 0
  var hasStockOptions : Bool = false
  var currentStatus : EmployeeStatus = .Active // sets with default EmployeeStatus
  enum EmployeeStatus {
    case Active, Vacation, LeaveOfAbsence, Temp, Retired

class CEO : Employee, ExecutiveMember { // shows that this class implements ExecutiveMember protocol
  overrride init() {  // does a special init for this object
    hasStockOptions = true

  var bonusAmount : Int {
    return 10000

  func returnFullTitle() -> String {
    return "Chief Executive Officer"

class CFO : Employee, ExecutiveMember { // can only implement one super class, but multiple protocols
  overrride init() {
    hasStockOptions = true

  var bonusAmount : Int {
    return 5000

  func returnFullTitle() -> String {
    return "Chief Financial Officer"

// creates protocol for objects that conform to this
**// protocol contains abstract method
protocol ExecutiveMember {  // protocol introduces method style, does not include implementation
  var bonusAmount : Int {

class Worker : Employee {


class TempEmployee : Employee {
  override init() { // sets default of this kind of employee to default .Temp
    currentStatus = .Temp

let ceo = CEO()
ceo.yearsWorked = 25
ceo.bonusAmount // implements protocol and returns bonusAmount
veo.currentStatus = .LeaveOfAbsence

let cfo = CFO()

let worker = Worker()

let temp = TempEmployee()
temp.returnFullTitle() // fails because does not implement returnFullTitle method


  • Build user interfaces in graphical environment
  • Only available as a project, not as playground
  • Any Any at bottom of layout shows the what kind of device this design is for
  • Control click on a label then drag to element you want to have it couple to in layout
  • ensures that the two elements stay close to each other when rendered on different layouts and screens
  • Create new view controller for any new screen you want
    select viewcontroller from side pane
    drag into the storyboard to be side by the other one
    control click on button in first view controller
    drag to other view
    now clicking button takes you to next view
  • ViewController.swift is stub that is build for first view controller
    Create swift file for second view controller
    make sure it implements view controller protocol
    Open storyboard
    set to class of secondviewcontroller

Set button action like this:

@IBAction func buttonPressed(sender : UIButton) {
  // button pressed

Segues allow view controllers to pass information between different view controllers.


  • Persistent between launches
  • Accepts keyed ints, strings, dates, not all kinds
  • **what does as? mean? // yes it’s an optional, but how does that apply to a for each as?

Interacting with Objective C

Swift string can be converted to NSString with cast

let str = "Test String"
let nsStr = str as NSString

  • true for nsdictionary, nsarray, nsnumber, etc
  • Subclass objective C object types in swift is allowed
  • limitation of no way to subclass a swift object in objective c

Creating button in objc vs swift

objc: UIButton *button = [UIButton buttonWithType: UIButtonTypeSystem];
swift: let button = UIButton(type: .System)

  • Swift automatically shortens enums
  • **objc API, you might find that LLVM shortens enum values
  • Using objective C and swift in the same project
  • Xcode creates a bridging header
  • import objective c header files
  • add properties
  • Then in implementation, write method
  • And copy the method signature to the bridging header file

Misc Swift notes:

  • In Swift 2, we can only use print() to write something to the output. Apple has combined both println() and print() functions into one.
  • The only Xcode version that supports Swift 2.0. Xcode 7 is currently in beta.
  • click on bottom left icon to bring up console in playground
  • printing a named parameter in the print function
  • print(“1”, “2”, “3”, separator:”—“)
  • Hold down option and click on method name, Shows method signature
  • Hold down command and click on method name, Jumps to method definition.

Lingering Questions

  • Is Core Data is available in swift playgrounds
  • What unique content is posted on swift.org?
  • Can I run swift on linux?
  • Where are the best Swift 2.0 problem sets online?