Swift Flashcards
python: To read a txt file into python, type
file = open(“/words.txt”, “r”)
words = file.read()
file.close()
python: To turn a list of words into a dict with the keys being the unique words and the values being their frequency in the list, type
from collections import Counter
counts = Counter(my_word_list)
swift: UIkit stands for
User Interface Kit
swift: var variableName only needs to be used
upon instantiation.
swift variable names should be written in
camelcase
swift: A constant is
an immutable variable
swift: To create a constant, type
let constantName = “value”
swift: To explicitly set the type of a variable, type
var myVariable: String = “value”
python: To turn a list of words into a dict with the keys being the unique words and the values being their frequency in the list, type
from collections import Counter
word_list = [‘apple’,’egg’,’apple’,’banana’,’egg’,’apple’]
counts = Counter(list1)
xcode: To show the console
click view / assistant editor / show assistant editor
swift: To print to the console, use the command,
print()
swift: To print something on the console on its own line, type
println()
swift: To evaluate a variable that is inside a string, type
println(“My name is (name_var)”)
swift: Interpolation is
evaluating a variable within a string
swift: To add a line break to a string type
\n
swift: To add a tab to a string type
\t
swift: To add an emoji to a string
click edit / emoji and symbols
swift: A double is
a float that can have 15 decimal places.
swift: If you do not specify the type “float” swift will assume a number with a decimal is a
double
swift: Booleans are written
lowercase
swift: To specify the type of a variable as a boolean, type
var my_var: Bool = false
swift: To convert a variable that is an integer into a Double, type
Double(myInt)
swift: When doing math, to control the order of operations, just use
parentheses
swift: When the operators in a math equation have the same priority, the equation is evaluated from
left to right
swift: To add 1 to an integer variable, type
myInt++
swift: To add 1 to an integer variable and assign it to another variable at the same time, you must put the
++ as a prefix. eg. ++myInt
swift: To subtract 1 from an integer variable in a short way, type
myInt–
swift: To evaluate to the opposite of the given boolean value, type
!false
swift: To specify that an array is a list of only strings, type
var myList: [String] = [“String1”, “String2”]
swift: To append items to the end of an array (using +=), type
myArray += [“New item1”, “New item2”]
swift: To return the attribute of an array that is the sum of the items, type
mylist.count
swift: To append a new item to an array, type
myArray.append(“new item”)
swift: To pop the last item of an array, type
myArray.removeLast()
swift: To remove an item from an array by its index, type
myArray.removeAtIndex(2)
swift: To insert a value into an array at index 2, type
myArray.insert(“value”, atIndex: 2)
swift: To create a single line comment in swift, type
//
swift: To create a dictionary, type
myDict = [“key”: “value”, “key”, “value”]
swift: To add a new dictionary item to myDict, type
myDict[“new key”] = “new value”
swift: myDict[“key name”] returns an
optional
swift: To pop/remove a dict item based on its key, type
myDict.removeValueForKey(“key name”)
swift: To make a for loop, type
for item in myArray {
println(item)
}
swift: to create a for loop for a range of 1 to 10, type
for item in 1…10 {
println(item)
}
swift: to create a rang of 1 to 10 using the greater than symbol, type
1..>9
swift: To make a loop that runs once before validating a condition, type
i = 0
do {
print(“string”)
} while i
swift: To create a while loop that increments, type
i = 0
while i
swift: To create a for loop that increments on one line, type
for var i = 0; i
swift: To create an if, else if, else, chained statement, type
if i 3 { print("more") } else { print("equal") }
to create a for loop that prints a string when the item is equal to 3 or 4, using a switch statement, type
for item in myArray { switch item { case 3, 4: print("string") default: print("") } }
swift: the “and”, “or” and “not”, operators are
&& || !
swift: To create a function, type
func functionName() {
}
swift: to define a function with parameters, type
func functionName(param1: Int, param2: String) {
}
swift: To create a function that has a return, you must
specify the return type, e.g.
func functionName() -> int { return 5 }
swift: To label function parameters so they are easily viewable in tab completion, type
func functionName(param1 1param1: Int, param2 param2: String) {
}
swift: When function params are labeled, you must
pass those labels in with the values when you call the function.
swift: When labeling your function parameters, you can succinctly make your param labels the same as the param names by typing
param1
swift: To declare the return of a function as a tuple with a boolean and a string, type
func functionName(param1: Int, param2: String) -> (Bool, String) {
}
swift: To create a tuple, use
parentheses and a comma
swift: To return the first index of a tuple, type
myTuple.0
swift: To unpack a tuple into variable names, type
var (name1, name2) = myTuple
swift: To set names to the indexes of a tuple that return from a function, so they can later be accesed as an attribute, type
func functionName() -> (name1: Bool, name2: String) {
}
swift: To unwrap the value of an optional, type
myOptional!
swift: If you have a function that only has a return if a condition is met, swift will make you
create another return for when the condition is not met.
swift: To be able to use a nil return type for when the required condition in a function is not met, you must
make the return type an optional by typing func functionName() -> String? { return nil }
swift: To safely unwrap an optional return with no chance of it crashing, type
if let myConstant = functionName("param") { myConstant }
swift: an optional can either have
a value or a nil
swift: The safest way to unwrap an optional is to use
an if let statement
swift: To turn a string into an integer, type
myString.toInt()
swift: To change a function call from a string to an Int, type
myFunction(“param1”)?.toInt()
swift: an enum allows you to create
a new type and set the possible values for that type.
swift: To create an enum for the days of the week, type
enum Days {
case Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
swift: One benefit of an enum is that
xcode will yell at you if you spell it wrong.
swift: To choose a member from an enum, type
Enumname.Membername
swift: To access the raw value of an enum member, type
Enumname.Membername.rawValue
swift: To assign raw values to each of the members of an enum, type
enum Days: Int {
case Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7
}
swift: Adding a raw value to enum members allows you to
perform arithmetic on them, e.g.
Day.Monday.rawValue - Day.Monday.rawValue
swift: If you assign a raw value of 1 to the first member of an enum, swift will automatically
add incremental raw values to the rest of the members.
swift: To create a function with a switch statement in it, type
func functionName(param1: Int) -> String { switch param1 { case 1...5: return "string" case 6...10: return "string" default: return "string" } }
swift: When create a switch statement, you must end the case statements with a
colon
swift: To create an instance of an enum member by its raw value, type
var enumInstance = EnumName(rawValue: value)
swift: var myEnumInstance = EnumName(rawValue: value) returns
an optional, just in case you pass in a rawValue that does not exist.
swift: The two ways to unwrap an optional are
bang or if let
swift: Each raw value for every enum member must be
unique
swift: To give an enum member an associated value that is a string, type
enum TypeName { class MemberName(String) }
let enumInstance = Typename.MemberName(“Set Associated Value”)
swift: To create an type member instance and pass in the associated value, type
var enumInstance = TypeName.MemberName(“Associated value string”)
swift: enum members must be
capitalized
swift: to add a method to an enum type, just
include the method in the brackets of the enum.
swift: For a method within an enum to make instances access themselves, the method must use
self.myAttribute
swift: By default the init() { } method does not
take any parameters or return anything.
swift: the init() { } method runs
upon instantiation
swift: To use the init() { } method to set an attribute of every new instance automatically, type
init() {
self = TypeName.MemberName
}
swift: A struct is a
class with attributes and methods
swift: To create a struct with two attributes, type
struct Structname {
var attribute1: String
var attribute2: String
}
swift: To overwrite a structs init() { } method (3 attributes) with a custom one that takes two parameters and also sets a default value to the third attribute, type
struct Structname {
var attribute1: String
var attribute2: String
var attribute3: String
init(Param1: String, Param2: String) { self.attribute1 = Param1 self.attribute2 = Param2 self.attribute3 = "default" } }
swift: To create an init method in a struct that will require a user input and then set that input to an attribute of the current instance, type
struct StructName {
var attribute: String
init (param1: String){ self.attribute = param1 } }
swift: If a struct has no init method, it will
require values for all of its attributes to be passed in automatically.
swift: If you decide to use an init method in a struct, make sure to include
all of the attributes that do not have a value.
swift: classes do not automatically
create the init method for the attributes present like a struct does. This means that I must either give the attributes values or create an init method.
swift: If the attributes of a class instance are var types, you can
change their value even if the instance you made is a constant.
swift: To make my class inherit from a ParentClass, type
class ClassName: ParentClass {
}
swift: To use this you must
class ClassName { var attribute = EnumName() }
have enums init method set the enum to a default value.
swift: To override a function inherited from a parent class, you must use the keyword
override func functionName() ->…
swift: In order to override a method from the parent class the new method must have
the same name, parameters and return type
swift: For a class that extends a parent class to call a method from the parent class that has been overwritten inside itself, you need to type
super.functionName(param1)
swift: To create a function with a default value for a param, type
func functionName(_ param1:Double = 10.0) {
}
Note: Since you provide the value then the underscore denotes it is optional.
swift: When overriding the init method from the parent class, any additional attributes must be
assigned first in the new init method above super.init()
swift: To override a parent classes init method but still initialize everything necessary from the parents init method, type
(2 parent class params and 1 subclass param)
init(param1: Double, Param2: String, Param3: String) {
self.attribute = param1
super.init(param2:Param2, Param3:Param3)
}
swift: a convenience initializer can only call
the designated initializer within its own class.
swift: To specify that an init method is a convenience initializer, type
convenience init(
swift: Initializers cannot call
a super classes convenience initializer
swift: The init method of a subclass will need to take in params for
all of its own attributes as well as all of the attributes from the parent class.
The parent classes attributes will then be passed into the super.init
swift: Computed attributes / properties can only be stored as a
var
swift: To create a computed property, type
var attribute3: Double {
return attribute1 * attribute2
}
swift: You cannot perform operations on
a Float with a Double
swift: To be able to set a value to your computed attribute using instance.attribute = “new value”, type
var attribute3: Double { get { return attribute1 * attribute2 } set { attribute = newValue } }
swift: in a computer attribute, the set { } methods newValue takes in the value from
instance.attribute = “new value”
swift: A “read/write” computed attribute requires the
get { } and set { } methods
swift: To create an attribute in a class that is an optional boolean, type
var attribute: Bool?
swift: A struct is a value type, meaning that
when you assign a struct to a variable, it copies whatever was in the struct and now there are two independent structs. So changing the new struct variable doesn’t change the first.
swift: A class is a reference type, meaning that
if you assign a class instance to a new variable, and then change an attribute of the new variable, the original instance is also changed.
swift: enums are also
value types
swift: attributes of a class must be set to
either let or var
swift: A convenience initializer is basically a way to
send defaults to the designated initializer except the ones you want to manually send in upon instantiation, to save time.
swift: To create a convenience initializer, type
convenience init(param1: Double) { self.init(param2: "default", Param 3: "default", param1: param1) }
xcode: The names of the 3 main panels from left to right are
navigator, editor, utility
xcode: To make xcodes storyboard take on the shape of a phone rather than a square
click on “w any h any” and drag the overlay window into the desired shape.
xcode: To see the icons you drag onto your storyboard
in the utility panel, click on “show the object library” circle icon, then click on the “icon view” button on the bottom left.
xcode: After adding a new icon to the story board it is a good practice to
click the “editor” menu, and “size to fit content”
xcode: To use the attributes inspector, click the
half diamond looking icon on the top on the utility panel.
xcode: TO change the size of the phone simulator
go to the “window” menu, and the “scale”.
xcode: To rotate the screen
in the simulator type command left
xcode: To center a button on the storyboard
Open the “document outline”, the blue button on the bottom left. select the button. Click the blue button on the bottom right called “align” and add the vertical and horizontal constraints.
xcode: in images.xcassets, an image set it
a set of the same image in a few sizes
xcode: If switching a button from text to image, you must
remove the title from the utility panel.
xcode: The iphone 3, 4/5, 6 use the pixel densities
1x, 2x, and 3x respectively.
xcode: To connect a UI element to code
hold control, then click and drag the element to the assistant editor
xcode: To make a UI element that you made hidden in the attribute inspector no longer hidden, type
elementName.hidden = false
xcode: The shortcut to view files navigator is
command 1
xcode: IBoutlets are usually
weak
xcode: The most common type of button action is
touch up inside
xcode: To change the text of a UILabel instance, type
instanceName.text = “new label”
swift: If you create an array within a function, its scope is
limited to only inside the function.
swift: Commands that need to happen immediately should be added to the
viewDidLoad() method
swift: To generate a randon number, type
let diceRoll = Int(arc4random_uniform(7))
xcode: An orange line in the story board means that
the positioning of the UI element is ambiguous
xcode: To fix ambiguous positioning of UI elements, press
the triangle button on the bottom right of the story board called “resolve auto layout issues”, then press “reset to suggested constraints”
xcode: To make the size of a label auto adjust to a string
set the lines attribute to 0
xcode: The app icons you upload should be
squares because xcode automatically rounds the corners
swift: an @IBOutlet functions as
an import of an object which you can use to alter it’s attributes.
swift: the launch screen is
the screen that temporarily displays after the app is launched
swift: The states for a button are
highlighted
selected
normal
disabled
swift: When setting constraints using the pop up on the bottom right, make sure to set
Update Frames: to “Items of new constraints”
Note: This places your element where your constrint will put then on the device.
swift: Outlets should be placed … while Actions should be placed
Outlets: Top of the view
Actions: Bottom of the view
swift: To set a views background color attribute to orange, type
view.backgroundColor = UIColor.orangeColor()
swift: When creating a new view, instead of starting a new blank swift file, use
Cocoa Touch Class under iOS source
swift: New view controller files should be a subclass of
UIViewController
swift: When you delete an action from the view controller you must also delete
the reference to that action by right clicking on the object in the storyboard.
swift: To make a button that upon being clicked takes you to another view
hold control, then drag the button onto the next view in the storyboard.
swift: To change the title of a button, type
buttonInstance.setTitle(“New Title”, forState: .Normal)
swift: To add a navigation bar
select a view, then in the menu, editor / imbed in / navigation controller
swift: a shortcut to make a label resize to fit all of the text in it is
command =
swift: One UI element can have both
an Outlet and an Action
swift: Initial setup for a view should be called in the function called
viewDidLoad
swift: If you are triggering animations, it is preferable to start them in the function called
viewDidAppear rather than viewDidLoad
swift: The difference between viewDidLoad vs. viewDidAppear is
viewDidLoad only runs once and after the view is constructed. After loading to memory it doesn’t run again.
viewDidAppear runs anew every time the view appears.
swift: An example of a hierarchical navigation is
the iphone settings.
swift: For a quick one off action a user must take, the preferred segue is
modal
swift: To create a new view, just
drag a view controller element out of the object library
swift: To send information from one view to another you must use the current views
prepareforSegue:Sender: method
swift: To be able to choose a segue for your prepareforSegue:Sender: method, you must first
give the segue an identifier in the attributes inspector
swift: To access the outlets on the destination view controller from within the current one, use
segue.destinationViewController as ViewControllerName
swift: To send from the current view to the next using a segue, in the curent view you must type
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "segueIdentifier" { let instanceOfNextViewController = segue.destinationViewController as! TitleOfViewController TitleOfViewController.variableInNextController = "value" } }
swift: when trying to send info from the current view to the next, your app will crash if you try to
create an instance of the next view in the current one and then change a UI element before the view has loaded.
swift: To send information from the current view to the next, you must
create a var on the next view and in the current view create an instance of the next view controller and set the value of the var. Then only apply that var to a UI element in the viewDidLoad() method for after the view loads.
swift: for images views, you must specify the
hight and width constraints in the pin menu, next to the align menu
swift: When you upload vector images, to set xcode to recognize them as vector
select the image and in the attributes inspector, set scale factors to Single Vector.
swift: To turn anyObject into a string, type
as String, after it
swift: To assign a ViewController to a view
Go to the identity inspector and set the class to the name of the new ViewController file.
swift: The library to use when playing audio is called
AVAudioPlayer
swift: If you want a variable that is being assigned inside a function to have global scope, you must
initialize the variable outside the function, and then update it within the function.
swift: always make sure that after you create a variable with var, that you do not
use var on the same variable again.
swift: To create a button that plays an audio file, type
import AVFoundation
var audioPlayer: AVAudioPlayer!
override func viewDidLoad() { super.viewDidLoad() if var filePath = NSBundle.mainBundle().pathForResource("movie_quote", ofType: "mp3") { var filePathURL = NSBundle.mainBundle().URLForResource("movie_quote", withExtension: "mp3") audioPlayer = AVAudioPlayer(contentsOfURL: filePathURL, error: nil) } }
@IBAction func playAudio() {
audioplayer.stop()
audioPlayer.play()
}
swift: To change the speed of the AVAudioPlayer playback, type
audioPlayerInstance.enableRate = true audioPlayerInstance.rate = 0.50
swift: To check the exact size of a constraint, just
click on it and check the attributes inspector
swift: To declare the time of an AVAudioPlayer instance to a certain time in the audio file, type
audioPlayerInstance.currentTime = 0.0
swift: When renaming a ViewController.swift file, the 4 things you must do are
Change the file name
Change the name of the class inside the file
Change the comment at the top of the file
Go to the story board and click on the view, then in the identity inspector, select the new class name.
swift: To format a date, type
let currentDateTime = NSDate() let formatter = NSDateFormatter() formatter.dateFormat = "ddMMyyyy-HHmmss" let recordingName = formatter.stringFromDate(currentDateTime)+".wav"
swift: When assigning a function into a var, do not
add the parentheses
swift: To filter an array, type
var filteredArray = fullArray.filter(functionThatReturnsTrueOrFalsePerItem)
swift: The nested function in a closure has
access to variables assigned inside the function it was nested in.
swift: closures maintain
the value of variables inside the nested functions.
swift: When assigning a closure into a var,
add the parentheses
swift: Core data allows you to
save settings that you’ve changed in your app
swift: To choose a file to show in the assistant editor,
hold alt and click on it
swift: To change the launch screens view, change the
LaunchScreen.xib file in the navigator
xcode: To clean xcode’s cache, press
command shift k
xcode: to force a build of your code, press
command b
xcode: To go to the home screen on the mac ios simulator,
in the simulator, go to the “hardware” menu and click “home”
swift: To be able to assign raw values to enum members you must
define the raw values type. e.g.
enum EnumName: Int {
}
swift: To enter the swift repl, type
swift
swift: To exit the swift repl, type
control d
swift: To change the background image, type
under viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named: “background.png”))
swift: The properties of the UIView class that are animatable are
frame, bounds, center, transform, alpha, backgroundColor, contentStretch
swift: To make the background color of my view red, type
myView.backgroundColor = UIColor.redColor()
swift: To create two views that switch with an animation, type
self. container.frame = CGRect(x: 60, y: 60, width: 200, height: 200)
self. view.addSubview(container)
self. redSquare.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
self. blueSquare.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
self. redSquare.backgroundColor = UIColor.redColor()
self. blueSquare.backgroundColor = UIColor.blueColor()
self. container.addSubview(self.redSquare)
UIView.transitionWithView(self.container, duration: 1.0, options: UIViewAnimationOptions.TransitionCurlUp, animations: { views.frontView.removeFromSuperview() self.container.addSubview(views.backView) }, completion: { finished in // code to be applied once the animation has completed })
swift: To create a simple rotation animation, type
UIView.animateWithDuration(0.5, animations: { self.myView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
})
python: if functions are a first class citizen that means you can
pass a function into a function
assign a function to a variable
python: In functional programming, your functions should not have
side effects
python: To create a lambda function, type
(lambda x: x*5)(2)
python: **my_dict converts {“key”: “values”} to
“key” = “value”
python: a closure is
a function that returns a pointer to a function nested inside of it, which is then assignable into a variable.
e.g.
closure_var = closure() (which returns a pointer to a nested function)
closure_var(param1)
python: A closure must return
a pointer to an inner nested function (it is the name of the function with no parentheses)