SWIFT2
operators can be set into 3 categories
1. Unary — operate on single target 2. Binary — operate on 2 targets 3. Ternary — operate on 3 targets
candidates for enums
1. days in week 2. months in year 3. planets in a system 4. categories of products 5. types of vehicles 6. classification of species 7. roles of user
Views are responsible for:
1. handling content on the screen 2. handling user interaction 3. And managing the layout for any subviews in the view
2 methods to check whether an optional holds a value:
1. if let, and != nil var favoriteFood: String? if let food = favoriteFood { print(food) } favoriteFood = "worms" if favoriteFood != nil { print(favoriteFood!) }
Nil coalescing operater
??. Used when working with optionals where we have a variable that may have a value, or might be nil. var personalSite : String? let defaultSite = "http://www.lynda.com" var website = personalSite ?? defaultSite
What is a raw value
A raw value is a value that is assigned to a member of an enum.
functions
A sequence of instructions that perform a specific task, packaged up as a unit. func myFunction(){ println("this is a simple function") } myFunction() must use type annotation when using parameters also referred to as sub routines or procedures
Struct initializers
A struct can have an init method to provide initial values for the stored properties.
Struct stored properties
A struct has stored properties. It is known as stored properties because it has stored values.
Struct
A struct provides structured data that can hold multiple variables or attributes and behavior. These are what are known as properties (attribute) and methods (behavior). struct Car { var doors: Int var wheels: Int }
dictionary
AKA associative array, map, hashtable. Key / Value pair. not in a specific order. cannot have duplicate keys.
How do you unwrap an optional
Add a bang to the end of the variable
Arguments help us
Adopt generic behavior to our particular needs
In portrait orientation, all iPhones fall under:
Any Width, Regular Height. There's no way to target each device specifically.
API
Application programming interface — which is considered to be a black box.
Structures
Are simple containers for information that belongs together
We can creat a subclass
By putting its superclass after a colon.
computed property
Can only be variables. Don't store a value, returns a value based on other properties or calculations. A computed property should have a setter method for conveinence
Functions can have parameters with
default values which are assigned in the parameter. func doStuff(stuff stuff:String = "Walk dog"){ print(stuff) }
properties and methods are known as a struct's, emum or classes':
definition
deinit
deinit { // any necessary cleanup code such as closing resource connections }
When transitioning from a master to a detail view controller using a segue, which property do we use to access the detail view controller
destinationViewController
base class
does not subclass or inherit from any other class class Product { }
synchronous task:
doing something at once, and waiting until it is done
In an object we can access stored properties that are inside the definition of the object by using:
dot notation
To access properties we use the:
dot notation
We can call methods on objects using the:
dot notation
closure
lambda, block, anonymous functions. Cool bit — functions that accept a closure
Swift is a type safe
language
what keyword is implied with for in statement?
let
string interpolation
let final = "\(str1) \(str2) \(str3)"
concatenation
let final = str1 + str2 + str3
Sometimes its necessary for a subclass to adapt an inherited function to its particular needs by using the:
override keyword: override func wash(){ print("Car is clean baby!") }
When we add properties to the subclass we must add which keyword to the new init method?
override. override init(){ newProp = "dog" super.init() }
We can use one function in another function as a:
parameter
You can run a switch inside a function over a:
parameter
Function inputs are called:
parameters
When assigning a function to a constant or variable you do not use:
parenthesis
Type methods belong to the type it self, not the
particular instance of the class
Modifying a function to accept inputs allows us to
pass arguments to it
The job of a function is to
perform repetetive tasks
a reference type:
points to the actual value
To pass information from one view controller to another in a direct relationship using a segue we use the current view controllers'
prepare for seque method — prepareforSegue:sender
Adding the keyword final in front of a method or class
prevents the method or instance from being overridden
add item to dictionary
states["FL"] = "Florida", if key exists it gets overridden -- otherwise it adds it. Long form : states.updateValue("Nevada", forKey: "NV")
history of let
stems from math
Properties inside classes are known more formally as:
stored properties. They store the data inside each instance of the class
Within interface builder we work in a:
storyboard
A class is very much like a:
struct
struct example
struct Task { var description: String var status = Status() init(description: String){ self.description = description } }
String, Array, and Dictionary are implemented as:
structures
When referring to class hierarchy we say
subclass and superclass
To remove a key value pair you can use
subscript notation or a method. Assign nil via subscript: myDictionary["KO"] = nil, using a method: myDictionary.removeValueForKey("RN")
Types are set for both
keys and values [String: String]
when we create a new variable we say we are
declaring a variable
Segue objects manage transitioning from one:
view controller to another
The window acts as a container for the many
views that make up your app
In iOS you use windows and
views to present content on the screen
Interface builder lets us create our apps:
visually
remainder operator
%. Modulo. Tells leftover
unary increment operator
++
Runtime errors are errors that occur when we run our application, in contrast to compiler errors
, which is code that needs to be fixed before it can be run.
half-open range operator
..< — does not include the number on the right 0..<100
get count
.count, isEmpty
looping through arrays:
// Using while var index = 0 while index < todo.count { print(todo[index]) index++ }
strong type
// dictionaries are strongly typed. The keys and the values are separately typed var products : [Int:String]
initializer with parameter
//initializer with parameter init(name: String){ self.name = "John Doe" self.score = 10 }
Image views are ui elements that display:
1 image or an animated series of images
benefits to switch statements
1. A switch statement lets you switch on a range of values 2. A switch statement combines multiple pattern matches in a concise syntax 3. A switch statement can infer the type being switched on and provide compiler checks 4. A switch statement requires you to be exhaustive and consider every path your code can take
Three types of navigation styles
1. Hierarchical 2. Flat 3. Content or experience Driven
Why use structs?
1. Intended for straight-forward data structure tasks 2. Generally use them when your internal properties are all going to be simple value types If you would have created as a class in another language, you would use a class in swift.
Three parts of XCode
1. Interface builder — interface of app 2. Editor - write code 3. Debugger - fix problems
Advantages of value types:
1. Only one owner. 2. No dependencies on other owner 3. Copying is cheap over time
Two ways to provide fore initial values for class properties
1. Set value to empty string or other default value. 2. Create init method
Four pillars of iOS development
1. Tools - Xcode 6, iOS Simulator, Instruments 2. Language — Swift, Design patterns, supporting Frameworks 3. Design — App flow, Correct UI, Apple HIG 4. Rules of programming iOS — Default behavior, Customizing behavior, Signing and submitting apps
convenience initializer example:
Convenience inits call self.init class Product { let name: String let price: Double init(name: String, price: Double){ self.name = name self.price = price } } class Hotdog: Product { let relish: Bool init(relish: Bool, name: String, price: Double){ self.relish = relish super.init(name: name, price: price) } convenience init (name: String){ self.init(relish: true, name: name, price: 1.44) } } var chicago = Hotdog(name: "Chicago") chicago.price
How to add raw values to enum
Define type. enum Coin: Double { case Penny = 0.01, Nickel = 0.05, Dime = 0.10, Quarter = 0.25 }
Master Detail:
Design pattern where one screen shows high level of information. Clicking on an item on the master screen takes user to the detail view on another screen
asynchronous task:
Doing something behind the scenes and continuing the main work regardless of whether or not the background task is complete
enum
Enumerated types or Enums allow you to define a datatype with a list of possible values. Create one type that lets you group several related values together
real world emum
Helps prevent errors by defining set values to test againsts
Navigation can be broken down into three main style:
Hierarchical, Flat, Content or experience driven
HTTP
Hyper text transfer protocol
We can access an overridden function in the super class by
Including the keyword super
Except for optionals we need to
Initialize every instance variable
converting values
Int(), Double(), String()
basic data types
Int, Float, Double, String, Character, bool
A struct
Is a data type that bundles information
optional variables
Let us describe a situation where sometimes we have a value and sometimes we don't. Set like this: var temp : Int? This results in 'optional' text. To remove 'optional' text, add exclamation point after var: println("The temperature is \(temp!)") Referred to as forced unwrapping
Inside classes functions can
Model behavior
Classes
OOP -- object oriented programming
Thread:
Path of execution for code
To override an inherited function we
Reimplement it after the override keyword
How do we return multiple values from a function
Return via an array or a tuple
Stored properties in Structs
Store constant and variable values as part of a instance of a particular struct
stored properties
Structs can have stored properties which can be constants with default values
Properties associate values with a particular:
Structure, class, or enumeration
overflow checking
Swift does not allow values to overflow. If needed, overflow operators are available. &+, &-, &*, &/ &%
designated initializer
The initializer that must be used when creating an instance of your class. There must be one available for a class.
Designated initializer
The initializer that must be used when creating an instance of your class. There must be one per class.
concurrency
The notion of multiple things happening at once
return a value
The return type of a function comes after input parameters. Must have reachable return statement. func myFunction() -> String { return "Hello" }
short circuit evaluation
These operators are lazy and would like to do the least amount of work possible. They return true or false after the first succesful test
T or F — A normal variable must be initialized before we attempt to use it
True
T or F : we can define 2 names for the same parameter
True. A function parameter can have a different internal and external name. We are changing the internal parameter
A view is an instance of the:
UIView class
Forced unwrapping
When we are sure the optional has a value. Must test if value is not nil
We can use a struct
Whenever we want to encapsulate a few simple values
operators
a && b. Joins one logical operator to another. a || B ! means not
types
a construct to represent different kinds of data like letters or numbers
string interpolation can include
a function call
Convenience initializer are:
created so that any if any default values can be specified, they are specified and you only have a minimal set of parameters
reference type
a reference to the original value is copied. Passing a reference to a location in memory
programming is
a series of instructions
What is an instance
a struct is a blue print, from it you can create instances
value type
a value type is a type whose value is copied when it is assigned to a variable or constant, or when it is passed to a function • Has only one owner • No dependencies on other owners • copying is cheap over time • comparing values is easy
The showing and hiding of information is handled by:
a view controller
protocol
a way to standardize some behavior across classes without worrying about inheritance or any formal relationship.
An entry point is a way to
access a view controller
A segue overrides an:
action
target actions
action and target is tied to event
extensions
add methods and properties to existing types
How do you create an optional?
add question mark to end of type, such as: var temp : Int?
typing
all variables are of a specific data type
Struct
allows you to create a new datatype
When we provide a value for a parameter it is called:
an argument
The filter function filters items in an array and returns:
an array
Simple statements are the most common and consist of either:
an expression or a declaration.
Logical operators unfold their true potential in combination with:
an if statement
when you create a variable with a class or struct it is called:
an instance
navigation bar
appear on the top of an app screen, just below the status bar and displays current level you are on and the path you took to get there
simplest way to add item to array is the
append method: todo.append("pup to vet")
Another way to add items to array is by
appending an array: todo += ["order book"]
Functions can be used inside other functions using the
arguments from the wrapping function
two built in collection types
array, dictionary -- arrays are zero-based. Arrays are type-safe. No mixing and matching of types. Mutable when created with var. Immutable when created with let
A variable number of parameters can be treated as an:
array. func sum(numbers: Int...){ var s = 0 for number in numbers { s += number } print(s) } sum(1,2,4)
Higher order functions are functions that take one or more functions:
as their input
raw values with emumns
assign raw values to enums to easily do something with those values. Must be unique
Putting information into a variable is called
assigning
To add a new key to a dictionary use the:
assignment operator: myDictionary["KO"] = "knocked out"
Each scene has an:
associated view hieracrcy
To solve problems with layout in iOS we use:
autolayout
Property observers fire:
before and after a property is modified. willSet {//right before the change} didSet{//right after the change} var weight = 100 { willSet { print("about to change name to \(newValue)") } didSet { print("changed weight from \(oldValue)") } }
Compiler errors need to be fixed:
before our app can run
1 + 1 is an example of
binary
square brackets are also referred to as
box brackets
parameters
by default input parameter is contstant, not a variable, using var when you declare makes it mutable
A view consist of everything a user
can see
Using self inside the init method helps keep the code clear. Also, self is specified because of a naming conflict. Self refers to the stored property, and the second is the local parameter that has been passed.
class Heros { let name: String let level: Int init(name:String, level: Int){ self.name = name self.level = level } }
class
class Player { // properties var name : String = "John Doe" var score : Int = 0 // methods func description() -> String { return ("Player \(name) has a score of \(score)") } } // instantiate a new Player object var jake = Player()
inheritence
class PremierPlayer : Player { // new class name followed by colon and class we want to inherit from }
Super.init example
class Presidents: Heros { let country: String init(country: String, name: String, level: Int) { self.country = country super.init(name: name, level: level) } }
designated initialer example
class Product { var title: String var 120: Double = 0.0 init(title: String, price: Double){ self.title = title self.price = price } }
class example:
class Shape { var sides: Double var name: String init(sides: Double, name: String){ self.sides = sides self.name = name } } class Square : Shape { var sideLength: Double var area: Double { get { return sideLength * sideLength } set { sideLength = sqrt(newValue) } } init(sideLength: Double , sides: Double, name: String) { self.sideLength = sideLength super.init(sides: sides, name: name) } convenience init(sideLength: Double){ self.init(sideLength: sideLength, sides: 4.0, name: "Square") } } var theSquare = Square(sideLength: 20.3)
key differentiator between struct and class:
class is reference type, struct is value type
A push segue adds a view to a navigation stack in which the information is:
clearly connected to the previous screen
deinit is used to
close connections to resources
tuple
collection of values. Returning a tuple: func getCurrentSongAndDuration() -> (String, Int){ return("Moonlight in Vermont", 210) } Set of values wrapped in parenthesis
The model
collects data, performs logic on it, and gets it ready for use
syntax
commands, special words, and punctuation you use to put together a program
The model does not
communicate with the view
comparison operators are binary operators used to
compare the indentity of two values, return true or false
type inference
compiler looks at code and infers type. Let compiler infer if it is obvious, if not declare it.
Another type of property is known as a
computed property. Uses getter and setter methods
We need to be sure to write:
concurrent code in Swift
When uploading or downloading creating a:
configuration object is the first step you must take.
You can assign a function to a:
constant or varible
Parameters are assigned as:
constants, but can be changed to a variable using the var keyword
to represent the type of an array we use the type of its:
content and place within square brackets -- [String]
a value type makes a:
copy
range operate
create a range between two numbers. 0...3 -- Closed range operator for number in 1...10 { print("\(number) times 5 is equal to \(number * 5)") }
let
creates contstant
When returning the value as a tuple we have access to the return value via
dot notation. func doStuff(stuff stuff:String = "Walk dog", stuff2:String = "Walk dog Again") -> (String, String){ return(stuff, stuff2) } let result = doStuff() result.0
A views purpose is to
draw to the screen and display data from the model object
Instance level class properties have that name because
each instance of the class receives those values
When returning tuples, you can assign a name to:
each return type. func doStuff(stuff stuff:String = "Walk dog", stuff2:String = "Walk dog Again") -> (Stuff1: String, Stuff2:String){ return(stuff, stuff2) } let result = doStuff() result.Stuff1
to enable push segue we must
embed our view controller inside a navigation controller -- editor/embed in/navigation controller
enum example using self
enum Day : Int { case Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday func daysTillWeekend() -> Int { return Day.Saturday.rawValue - self.rawValue } } var day = Day.Monday day.daysTillWeekend()
example of initializer method with emum
enum Day : Int { case Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday init() { self = .Monday } func daysTillWeekend() -> Int { return Day.Saturday.rawValue - self.rawValue } } var today = Day()
enum example
enum Day { case Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } func weekdayOrWeekend(dayOfWeek dayOfWeek: Day) -> String { switch dayOfWeek { case Day.Monday, Day.Tuesday, Day.Wednesday, Day.Thursday, Day.Friday: return "It's a weekday" case Day.Saturday, Day.Sunday: return "Yah! It's the weekend" default: return "Not a valid day" } } weekdayOrWeekend(dayOfWeek: Day.Monday)
raw value assignment example
enum Day: Int { case Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7 }
enums
enum SeatPreference { //seat preference is the new type // each case is a member value of the enumeration // typically written with uppercase first letter case Window case Middle case Aisle case NoPreference }
enum example
enum Status { case Doing, Pending, Completed init() { self = .Pending } }
associated values (with enums)
enum Status { case Success(String) case Failure(String) } let downloadStatus = Status.Failure("Network connection unavailable") When you want to pass it a value, you use the same construct. Lets you add an associated value when you create a new instance of the type. When you want to extract the value you give it a constant in parenthesis. switch downloadStatus { case .Success(let success): print(success) case .Failure(let failure): print(failure) }
Buttons have a few different states which is an:
enum called UIControlState. The default state is normal. Other states are: highlighted, selected, and so on
A closure is a combination of a function and an:
environment of captured variables.
Single responsibility principle:
every class should have single responsiblity
var
every variable in Swift is declared with keyword var. A variable is a way of holding on to some data
Control flow statements are good for:
executing code based on logical conditions
together, the operands and the operator is known as an
expression
calling a function is an:
expression, so we can assign the value to a variable or a constant
Parameters in a swift function can have both a
external parameter name and an internal parameter name
Functions are treated as:
first class citizens or objects
adding to the end of an array
flavors.append("new flavor") flavors += ["Flavor"]
insert at specific location
flavors.insert("fudge", atIndex: 2)
remove items
flavors.removeLast() flavors.removeAtIndex(3)
A structure is a:
flexible data type that allows you to group together related values and model them as a unit
Control flow statements are used to control the:
flow of execution in a program.
iterate over values
for (key, value) in states { println("\(key) is short for \(value)") }
for in
for individual-item in some-collection { }
@IBAction lets:
interface Builder know that we have a method in code that is associated with a button
A while loop can be nested inside a:
for loop var y = 1 for x in 1...5 { while y < 2 { print(y) y++ } }
We can return one function:
from another
example of map function:
func doubler(i : Int) -> Int { return i * 2 } let doubleFunction = doubler doubleFunction(20) let numbers = [1,2,3,4,5] let doubledNumbers = numbers.map(doubleFunction)
struct methods
func fullName() -> String { return self.firstName + " " + self.lastName }
isDivisible function
func isDivisible(num1: Int, num2: Int) -> Bool?{ if(num1 % num2 == 0){ return true } else { return nil } } if let result = isDivisible(13, num2: 3){ print("divisible") } else { print("Not Divisible") }
pass in a parameter to function
func myFunction( name : String ){ println("Hello \(name)") } myFunction("Jane")
Using default parameter values
function myFunction (name : string = "John Doe") { } must use named data if you want to override. myFunction(name: "Jane")
Methods are:
functions associated to a particular type
The 2 actions associated with properties are:
getting a value and setting a value
getter and setter methods
get{} or set{} goes inside computed properties class Temperature { var celsius: Float = 0.0 var fahrenheit: Float { get { return (celsius * 1.8) + 32 } } }
Closures allow us to to build up:
higher order function
switch
http://austinzheng.com/2014/12/16/swift-pattern-matching-switch/ A switch statement compares some value so it can compare it against several matching patterns. evaluating a single item reacting to multiple possible values. Switch statements must be exhaustive. Can provide range of values with range operator switch valueToConsider { case value1:respond to value1 case value2: respond to value2 default: do something else } using an array and for in: let airportCodes = ["LGA", "LHR", "CDG", "HKG", "DXB", "JKL"] for airportCode in airportCodes { switch airportCode { case "LGA", "SFO": print("La Guaria") case "LHR": print("That is lhr") default: print("I Dont know") } } You can test on multiple cases separated by a comma You can also switch over a range of values: var randomTemp = Int(arc4random_uniform(UInt32(150))) switch randomTemp { case 0..<32: print("Dont leave home") case 32...45: print("You will need a jacket") case 45...70: print("You will need a swearer") default: print("Too hot") } You can also run a switch on key, value pairs: let world = [ "BEL": "Brussels", "LIE": "Vaduz", "BGR": "Sofia", "USA": "Washington D.C.", "MEX": "Mexico City", "BRA": "Brasilia", "IND": "New Delhi", "VNM": "Hanoi"] for (key, value) in world { // Enter your code below switch key { case "BEL", "LIE", "BGR": europeanCapitals.append(value) case "IND", "VNM": asianCapitals.append(value) default: otherCapitals.append(value) } // End code }
Clean up your JSON with this:
http://prettyjson.com/
How to pull data from a pList
if let plistPath = NSBundle.mainBundle().pathForResource("CrazyInformation", ofType: "plist") { let currentCrazyInformation = NSDictionary(contentsOfFile: plistPath) } // inside view did load method
optional binding
if let result = states["NV"] { println("The state name is \(result)") } else { println("No matching key found") } // If key has a value, it gets assigned to constant
How to test for nil value in an optional
if temperature != nil { print(temperature!) }
convenience initializer
if there are any default values that can be specified, they are specified with a minimal set of parameters. Must start with keyword "convenience", which will call a designated initializer in return. It will only call the designated initializer of your current class. You cannot call the super initializer
Type inference
if values are obvious
a constant is known and an
immutable type
A navigation bar is contained
in a navigation controller
The navigation bar best enables us to navigate an
information driven app
push segue
information from the push segue is clearly connected to the previous screen
The most unique feature of a class is:
inheritance
sub class
inherits properties, methods, and initializers
initialzier
init(){ name = "John Doe" score = 0 }
You can also hardcode
initial values in an init method. init(){ name = "John Doe" score = 0 }
The process for preparing a struct for use is called:
initialization, and involves setting the value each stored property on the instance.
A subclass can have it's own init method as long as you:
initialize all the properties
You must initialize the properties that are in the current class first, before you:
initialize the properties that are in the super class
The advantage of optional properties is that they do not need to be:
initialized
Enums can have methods as well as
initializers. enum Size { case Small, Medium, Large init(){ self = .Small } }
To add element inside an existing array use the
insert method
string interpolation
insert new content into string. \("the string")
A variable created inside a function only exists:
inside that function
An instance method can only be called after we have an actual:
instance
Using the blueprint, we then create an:
instance
Self means the current:
instance of this class. self.name refers to the instance, not the class property
Except for optionals, we need to initialize every
instance variable
IDE
integrated development environment
A dictionary is an unordered list of
key-value pairs
When you don't want your stored properties to be mutated, you specify them as:
lets instead of vars inside the class construction. This is regardless of whether or not the instance is declared with let or var. They will be assigned in instantiation
view controller
links app data to visual appearance
A view controller:
links the app's data to its visual appearance
Any variable or constant created inside a function is called a
local variable
Just like other types, enums can contain:
methods
classes also have:
methods
One time actions are often presented in a:
modal
Object oriented programming is a style of programming where we:
model information into data structures.
a var is known as a
mutable type
when we call the function we add the
named parameters somefunc(par1: 100, para2: 200)
A property list or plist is a file that organizes data into:
named values and lists of values much like a dictionary or array. They are easy to read into NS dictionaries.
The hierarchical style of navigation is enabled by the:
navigation bar
In the setter method we use which keyword to set the value?
newValue
All networking code should be in a background cue to:
not block the UI and make it unresponsive
In regard to classes, you instantiate new:
objects of said class.
Size classes lets us build our app
on a canvas that is not tied to a specific device, but rather all devices
A struct does not need an initializer because:
one is provided by default.
infix operators go between the two
operands
the numbers 1 and 1 are referred to as
operands
array
ordered list of values. A list is a good mental model
The return keyword is used to:
output a value from a function
A navigation bar is contained in a navigation controller which is a:
programatic object which manages a the display of a hierarchy of views.
A navigation controller is a:
programmatic object that manages the display of a hierarchy or order of views
These instructions are provided by a
programming language
Structs can contain
properties and methods
enum methods
put functions inside enum declaration
Labels enable function calls to
read nicer. sayHello(to: "Pasan", and: "Gabe")
Classes are passed by:
reference — in other words, when assigned to another variable or passed to a function, a reference to the original object is passed
To remove an element inside an existing array use the
remove at index function, todo.removeAtIndex(0)
REST
representational state transfer.
POST is used to create, while GET is used to:
retrieve
a function's output is known as a
return type
When using a closure, the argument signature:
returns a value. func myFunc(y: Int -> Int){ // Give me a function } This represents a function that needs an Integer as an argument and returns another one. If we want to pass more arguments, we need to put them in brackets and separate them with commas: (Int, String, Double)
The logical AND operator:
returns the boolean value true if both operands are true and returns false otherwise.
The logical or operator:
returns the boolean value true if either or both operands is true and returns false otherwise.
Classes are yet another powerful concept we can use to make our code
reusable and understandable
Runtime errors only occur when we:
run our app
A storyboard is composed of multiple:
scenes
An enum can have a method that runs a switch on:
self, which allows a unique message to each type. enum Type { case Private, Work func description() -> String { switch self { case .Private: return "It is private" case .Work: return "It is work" } } } var myType = Type.Private myType.description()
function
self-contained chunks of code that perform a specific task
With the NSURL session API, your app creates a:
session object which carries out your networking tasks.
An initializizer is a special instance method that:
sets up our object ready for use.
Structs can have initializers by:
setting default values for stored properties struct Contact { let firstName: String let lastName: String func returnName() -> String { return self.firstName + " " + self.lastName } init(fName: String, lName: String){ self.firstName = fName self.lastName = lName } } var person = Contact(fName: "Hob", lName: "Hind"
@IBOutlet
shows text
In Xcode, pressing command-1:
shows your files
Self contained actions are not part of:
some other workflow
Optionals let us describe a situation where:
sometimes we have a value and sometimes we don't
operator is a :
special symbol or phrase that you use to check, change, or combine values
Subclassing helps us adapt generic code to our:
specific needs
repeat while:
statements in body are executed first, then the condition is verified. Guarantees one pass through body of loop: repeat { print("I am in a repeat loop!") counter++ } while counter <
to remove key/value pair
states["DE"] = nil, states.removeValueForKey("CA")
To access the overridden function, we can use the:
super keyword: class RaceCar: Car { var nitro: Bool? override func wash(){ print("Car is clean baby!") super.wash() } }
Whenever we implement init() in our subclass, we need to call:
super.init() to let the superclass do its initializing class Vehicle { var wheels: Int? } class Bike: Vehicle { override init(){ super.init() self.wheels = 2 } }
you can call the _____
super.int method after performing custom initialiazation
base class is a:
superclass of subclass
Before we can change the values of inherited variables in our init() function of a subclass, we need to allow our
superclass to set its initial values class Animal { var flying = false } class Swifty: Animal { override init() { super.init() self.flying = true } } var mySwift = Swifty()
A first class object:
supports all of the operations generally available to other types
The set of rules in programming is called
syntax
target action:
the action and its target is tied to an event, when the touch event occurs on the controller, the sequence is initiated
The advantage of objects is that we can associate a function with:
the data contained inside.
When using a setter method, the newValue keyword provides
the entire value
The Controller acts as:
the intermediary and controls the logic between the two
To grab items in array use
the item's index: let firstTask = todo[3] (subscript syntax)
Navigation bar shows two important things:
the level in the hierarchy as well as the path taken to get there
We can perform a function on each item in an array by using:
the map function
Lazy properties: the property is only accessed when
the method is called: lazy var bonus = getBonus()
A Method signature includes
the name, parameters, and return type
Method signature
the name, parameters, and the return type
We can override a method by using:
the override keyword
the parenthesis are where
the parameters go
The function that accepts another function can call:
the passed function using the name of the argument
When we press the button to initiate our segue, our view controller calls
the prepareforSegue:sender: method
The subclass is of type
the super class. This is what the colon means
When overriding methods in a subclass we have the option to call
the super.methodName()
string
the syntax for creating a string literal: let myString = "my string"
When the compiler infers the type for us we say
the type annotation is implicit
a NSURL configuration object is the first:
thing to do -- it provides the rules
No return type indicates that the return type is:
void. Also done like this: ->Void, ->()
No return type is a return type of:
void. We can explicitly declare this with the void keyword as the return type
We want to avoid:
tight couplings at all times
You use multiple views in different hierarchies :
to build how your app looks on the screen
Closures are especially useful when it comes to implementing callbacks because of the ability:
to capture variables
When a user interacts with the user interface the code gets:
top priority and is added to the main cue.
The best way to return multiple values is with a
tuple
You can also return a:
tuple from a function. func oneTwo() -> (Int, Int) { return (1, 2) } let (x, y) = oneTwo()
A method is a function associated to a specific:
type
Enums create a new:
type
methods are part of a:
type
a class is a new
type and is capitalized
Building blocks of programming language are called:
types
We use a combination of
types and grammar
Data can be many different
types.
There is a method that allows for updating key value pairs, it is called:
updateValue. myDictionary.updateValue("News you can use", forKey: "DB")
enum initializer
use init method inside enum: init(){ self = .Sunday } var today = Day() // results in Sunday as value gives the enum an initial value, this way you don't have to specify a value.
How to retrieve raw value
use keyword rawValue -- ex: Coin.Penny.rawValue
hierarchical
users make one choice per screen until they reach their destination
Stored properties store a:
value
We can return more than one:
value from a function using a tuple. Specify a tuple in the return type: func doStuff(stuff stuff:String = "Walk dog", stuff2:String = "Walk dog Again") -> (String, String){ return(stuff, stuff2) } doStuff()
Structures are passed by:
value — in other words when assigned to another variable or passed to a function, a structures value is copied
To create an instance of the struct named Lasagne:
var pastaDinner = Lasagne()
random number
var randNum = Int(arc4random_uniform(10))
Tuple return mult results
var result = getCurrentSongAndDuration() println("THE SONG IS \(result.0) and it's \(result.1)") Or, give names to the parameters: func getCurrentSongAndDuration() -> (name:String, length:Int){ return("Moonlight in Vermont", 210) } var result = getCurrentSongAndDuration() println("THE SONG IS \(result.name) and it's \(result.length)")
AnyObject and Any
var someObject : AnyObject var something : Any These are types, we can create variables and contstants of type AnyObject or
example of an optional with the if let syntax:
var temp: Int? temp = 10 if (temp != nil) { print(temp) } // optional binding if let theTemp = temp { print(temp) }
Structs and Classes are:
very similar
You can initiate multiple segues from a single
view controller
decompose tuple
ways to access individual items in tuple. One way is to assign a tuple to a tuple let myTuple = ("Jane", "Scott") let (myTuple1, myTuple2) = myTuple let (name, length) = getCurrentSongAndDuration() // names can be what ever you want
the keyword func indicates
we are declaring a new function
Request/response model:
we make a request in a certain place in a certain format
We need to pass a value to our initializer unless:
we provide initial values upon declaration or the variable is an optional
the curly braces are where
we specify our custom code
in order to keep parameters in the correct order
we use labels on the parameters
To pass information from one view controller to another using a segue
we use the current view controller's prepareforSegue:sender: method
'passing a parameter' is
whatever we specify between the parenthesis
A designated initializer is the main initializer to be used
when creating an instance of a class. There must be one for a class
orphaned outlet
when you create outlet and delete it in the code without getting rid of the interface builder connection
Initializer method with emum
whenever you create an instance with that enum, it will default to same value
loops
while, repeat while, and for. While example: var x = 0 while x <= 20 { print(x) x++ } repeat { statements } while condition
Each app has at least one:
window
A view manages a rectangular area within the
window in your app
for-in loop
works great for collection
can a subclass have its own initializer
yes
you must use string interpolation when
you are combining types
Struct Methods
you can create custom methods to extend its functionality or manipulate the data. func returnName() -> String { return self.firstName + " " + self.lastName }
Example of closure expressions
{(parameters) -> return type in statements }
Good candidates for emums
• Drop down menus for filters
Enum overview
• Let's you create a data type with possible values • Members can have raw values • Members can have associated values when creating an instance of that enum
enumerated types
• Lets you create a data type with possible values • Members can have Raw values • Members can have Associated values Great for limited set of values
overriding methods
• must use keyword override • the method signatures must match • when referring to the super class, use the keyword super