Swift Flashcards

1
Q

python: To read a txt file into python, type

A

file = open(“/words.txt”, “r”)
words = file.read()
file.close()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

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

A

from collections import Counter

counts = Counter(my_word_list)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

swift: UIkit stands for

A

User Interface Kit

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

swift: var variableName only needs to be used

A

upon instantiation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

swift variable names should be written in

A

camelcase

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

swift: A constant is

A

an immutable variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

swift: To create a constant, type

A

let constantName = “value”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

swift: To explicitly set the type of a variable, type

A

var myVariable: String = “value”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

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

A

from collections import Counter
word_list = [‘apple’,’egg’,’apple’,’banana’,’egg’,’apple’]
counts = Counter(list1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

xcode: To show the console

A

click view / assistant editor / show assistant editor

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

swift: To print to the console, use the command,

A

print()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

swift: To print something on the console on its own line, type

A

println()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

swift: To evaluate a variable that is inside a string, type

A

println(“My name is (name_var)”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

swift: Interpolation is

A

evaluating a variable within a string

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

swift: To add a line break to a string type

A

\n

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

swift: To add a tab to a string type

A

\t

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

swift: To add an emoji to a string

A

click edit / emoji and symbols

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

swift: A double is

A

a float that can have 15 decimal places.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

swift: If you do not specify the type “float” swift will assume a number with a decimal is a

A

double

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

swift: Booleans are written

A

lowercase

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

swift: To specify the type of a variable as a boolean, type

A

var my_var: Bool = false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

swift: To convert a variable that is an integer into a Double, type

A

Double(myInt)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

swift: When doing math, to control the order of operations, just use

A

parentheses

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

swift: When the operators in a math equation have the same priority, the equation is evaluated from

A

left to right

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
swift: To add 1 to an integer variable, type
myInt++
26
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
27
swift: To subtract 1 from an integer variable in a short way, type
myInt--
28
swift: To evaluate to the opposite of the given boolean value, type
!false
29
swift: To specify that an array is a list of only strings, type
var myList: [String] = ["String1", "String2"]
30
swift: To append items to the end of an array (using +=), type
myArray += ["New item1", "New item2"]
31
swift: To return the attribute of an array that is the sum of the items, type
mylist.count
32
swift: To append a new item to an array, type
myArray.append("new item")
33
swift: To pop the last item of an array, type
myArray.removeLast()
34
swift: To remove an item from an array by its index, type
myArray.removeAtIndex(2)
35
swift: To insert a value into an array at index 2, type
myArray.insert("value", atIndex: 2)
36
swift: To create a single line comment in swift, type
//
37
swift: To create a dictionary, type
myDict = ["key": "value", "key", "value"]
38
swift: To add a new dictionary item to myDict, type
myDict["new key"] = "new value"
39
swift: myDict["key name"] returns an
optional
40
swift: To pop/remove a dict item based on its key, type
myDict.removeValueForKey("key name")
41
swift: To make a for loop, type
for item in myArray { println(item) }
42
swift: to create a for loop for a range of 1 to 10, type
for item in 1...10 { println(item) }
43
swift: to create a rang of 1 to 10 using the greater than symbol, type
1..>9
44
swift: To make a loop that runs once before validating a condition, type
i = 0 do { print("string") } while i
45
swift: To create a while loop that increments, type
i = 0 | while i
46
swift: To create a for loop that increments on one line, type
for var i = 0; i
47
swift: To create an if, else if, else, chained statement, type
``` if i 3 { print("more") } else { print("equal") } ```
48
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("") } } ```
49
swift: the "and", "or" and "not", operators are
&& || !
50
swift: To create a function, type
func functionName() { }
51
swift: to define a function with parameters, type
func functionName(param1: Int, param2: String) { }
52
swift: To create a function that has a return, you must
specify the return type, e.g. ``` func functionName() -> int { return 5 } ```
53
swift: To label function parameters so they are easily viewable in tab completion, type
func functionName(param1 1param1: Int, param2 param2: String) { }
54
swift: When function params are labeled, you must
pass those labels in with the values when you call the function.
55
swift: When labeling your function parameters, you can succinctly make your param labels the same as the param names by typing
#param1
56
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) { }
57
swift: To create a tuple, use
parentheses and a comma
58
swift: To return the first index of a tuple, type
myTuple.0
59
swift: To unpack a tuple into variable names, type
var (name1, name2) = myTuple
60
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) { }
61
swift: To unwrap the value of an optional, type
myOptional!
62
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.
63
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 } ```
64
swift: To safely unwrap an optional return with no chance of it crashing, type
``` if let myConstant = functionName("param") { myConstant } ```
65
swift: an optional can either have
a value or a nil
66
swift: The safest way to unwrap an optional is to use
an if let statement
67
swift: To turn a string into an integer, type
myString.toInt()
68
swift: To change a function call from a string to an Int, type
myFunction("param1")?.toInt()
69
swift: an enum allows you to create
a new type and set the possible values for that type.
70
swift: To create an enum for the days of the week, type
enum Days { case Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
71
swift: One benefit of an enum is that
xcode will yell at you if you spell it wrong.
72
swift: To choose a member from an enum, type
Enumname.Membername
73
swift: To access the raw value of an enum member, type
Enumname.Membername.rawValue
74
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 }
75
swift: Adding a raw value to enum members allows you to
perform arithmetic on them, e.g. | Day.Monday.rawValue - Day.Monday.rawValue
76
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.
77
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" } } ```
78
swift: When create a switch statement, you must end the case statements with a
colon
79
swift: To create an instance of an enum member by its raw value, type
var enumInstance = EnumName(rawValue: value)
80
swift: var myEnumInstance = EnumName(rawValue: value) returns
an optional, just in case you pass in a rawValue that does not exist.
81
swift: The two ways to unwrap an optional are
bang or if let
82
swift: Each raw value for every enum member must be
unique
83
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")
84
swift: To create an type member instance and pass in the associated value, type
var enumInstance = TypeName.MemberName("Associated value string")
85
swift: enum members must be
capitalized
86
swift: to add a method to an enum type, just
include the method in the brackets of the enum.
87
swift: For a method within an enum to make instances access themselves, the method must use
self.myAttribute
88
swift: By default the init() { } method does not
take any parameters or return anything.
89
swift: the init() { } method runs
upon instantiation
90
swift: To use the init() { } method to set an attribute of every new instance automatically, type
init() { self = TypeName.MemberName }
91
swift: A struct is a
class with attributes and methods
92
swift: To create a struct with two attributes, type
struct Structname { var attribute1: String var attribute2: String }
93
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" } } ```
94
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 } }
95
swift: If a struct has no init method, it will
require values for all of its attributes to be passed in automatically.
96
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.
97
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.
98
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.
99
swift: To make my class inherit from a ParentClass, type
class ClassName: ParentClass { }
100
swift: To use this you must ``` class ClassName { var attribute = EnumName() } ```
have enums init method set the enum to a default value.
101
swift: To override a function inherited from a parent class, you must use the keyword
override func functionName() ->...
102
swift: In order to override a method from the parent class the new method must have
the same name, parameters and return type
103
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)
104
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.
105
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()
106
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) }
107
swift: a convenience initializer can only call
the designated initializer within its own class.
108
swift: To specify that an init method is a convenience initializer, type
convenience init(
109
swift: Initializers cannot call
a super classes convenience initializer
110
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
111
swift: Computed attributes / properties can only be stored as a
var
112
swift: To create a computed property, type
var attribute3: Double { return attribute1 * attribute2 }
113
swift: You cannot perform operations on
a Float with a Double
114
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 } } ```
115
swift: in a computer attribute, the set { } methods newValue takes in the value from
instance.attribute = "new value"
116
swift: A "read/write" computed attribute requires the
get { } and set { } methods
117
swift: To create an attribute in a class that is an optional boolean, type
var attribute: Bool?
118
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.
119
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.
120
swift: enums are also
value types
121
swift: attributes of a class must be set to
either let or var
122
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.
123
swift: To create a convenience initializer, type
``` convenience init(param1: Double) { self.init(param2: "default", Param 3: "default", param1: param1) } ```
124
xcode: The names of the 3 main panels from left to right are
navigator, editor, utility
125
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.
126
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.
127
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"
128
xcode: To use the attributes inspector, click the
half diamond looking icon on the top on the utility panel.
129
xcode: TO change the size of the phone simulator
go to the "window" menu, and the "scale".
130
xcode: To rotate the screen
in the simulator type command left
131
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.
132
xcode: in images.xcassets, an image set it
a set of the same image in a few sizes
133
xcode: If switching a button from text to image, you must
remove the title from the utility panel.
134
xcode: The iphone 3, 4/5, 6 use the pixel densities
1x, 2x, and 3x respectively.
135
xcode: To connect a UI element to code
hold control, then click and drag the element to the assistant editor
136
xcode: To make a UI element that you made hidden in the attribute inspector no longer hidden, type
elementName.hidden = false
137
xcode: The shortcut to view files navigator is
command 1
138
xcode: IBoutlets are usually
weak
139
xcode: The most common type of button action is
touch up inside
140
xcode: To change the text of a UILabel instance, type
instanceName.text = "new label"
141
swift: If you create an array within a function, its scope is
limited to only inside the function.
142
swift: Commands that need to happen immediately should be added to the
viewDidLoad() method
143
swift: To generate a randon number, type
let diceRoll = Int(arc4random_uniform(7))
144
xcode: An orange line in the story board means that
the positioning of the UI element is ambiguous
145
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"
146
xcode: To make the size of a label auto adjust to a string
set the lines attribute to 0
147
xcode: The app icons you upload should be
squares because xcode automatically rounds the corners
148
swift: an @IBOutlet functions as
an import of an object which you can use to alter it's attributes.
149
swift: the launch screen is
the screen that temporarily displays after the app is launched
150
swift: The states for a button are
highlighted selected normal disabled
151
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.
152
swift: Outlets should be placed ... while Actions should be placed
Outlets: Top of the view Actions: Bottom of the view
153
swift: To set a views background color attribute to orange, type
view.backgroundColor = UIColor.orangeColor()
154
swift: When creating a new view, instead of starting a new blank swift file, use
Cocoa Touch Class under iOS source
155
swift: New view controller files should be a subclass of
UIViewController
156
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.
157
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.
158
swift: To change the title of a button, type
buttonInstance.setTitle("New Title", forState: .Normal)
159
swift: To add a navigation bar
select a view, then in the menu, editor / imbed in / navigation controller
160
swift: a shortcut to make a label resize to fit all of the text in it is
command =
161
swift: One UI element can have both
an Outlet and an Action
162
swift: Initial setup for a view should be called in the function called
viewDidLoad
163
swift: If you are triggering animations, it is preferable to start them in the function called
viewDidAppear rather than viewDidLoad
164
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.
165
swift: An example of a hierarchical navigation is
the iphone settings.
166
swift: For a quick one off action a user must take, the preferred segue is
modal
167
swift: To create a new view, just
drag a view controller element out of the object library
168
swift: To send information from one view to another you must use the current views
prepareforSegue:Sender: method
169
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
170
swift: To access the outlets on the destination view controller from within the current one, use
segue.destinationViewController as ViewControllerName
171
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" } } ```
172
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.
173
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.
174
swift: for images views, you must specify the
hight and width constraints in the pin menu, next to the align menu
175
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.
176
swift: To turn anyObject into a string, type
as String, after it
177
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.
178
swift: The library to use when playing audio is called
AVAudioPlayer
179
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.
180
swift: always make sure that after you create a variable with var, that you do not
use var on the same variable again.
181
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() }
182
swift: To change the speed of the AVAudioPlayer playback, type
``` audioPlayerInstance.enableRate = true audioPlayerInstance.rate = 0.50 ```
183
swift: To check the exact size of a constraint, just
click on it and check the attributes inspector
184
swift: To declare the time of an AVAudioPlayer instance to a certain time in the audio file, type
audioPlayerInstance.currentTime = 0.0
185
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.
186
swift: To format a date, type
``` let currentDateTime = NSDate() let formatter = NSDateFormatter() formatter.dateFormat = "ddMMyyyy-HHmmss" let recordingName = formatter.stringFromDate(currentDateTime)+".wav" ```
187
swift: When assigning a function into a var, do not
add the parentheses
188
swift: To filter an array, type
var filteredArray = fullArray.filter(functionThatReturnsTrueOrFalsePerItem)
189
swift: The nested function in a closure has
access to variables assigned inside the function it was nested in.
190
swift: closures maintain
the value of variables inside the nested functions.
191
swift: When assigning a closure into a var,
add the parentheses
192
swift: Core data allows you to
save settings that you've changed in your app
193
swift: To choose a file to show in the assistant editor,
hold alt and click on it
194
swift: To change the launch screens view, change the
LaunchScreen.xib file in the navigator
195
xcode: To clean xcode's cache, press
command shift k
196
xcode: to force a build of your code, press
command b
197
xcode: To go to the home screen on the mac ios simulator,
in the simulator, go to the "hardware" menu and click "home"
198
swift: To be able to assign raw values to enum members you must
define the raw values type. e.g. enum EnumName: Int { }
199
swift: To enter the swift repl, type
swift
200
swift: To exit the swift repl, type
control d
201
swift: To change the background image, type
under viewDidLoad() self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png"))
202
swift: The properties of the UIView class that are animatable are
frame, bounds, center, transform, alpha, backgroundColor, contentStretch
203
swift: To make the background color of my view red, type
myView.backgroundColor = UIColor.redColor()
204
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 }) ```
205
swift: To create a simple rotation animation, type
UIView.animateWithDuration(0.5, animations: { self.myView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI)) })
206
python: if functions are a first class citizen that means you can
pass a function into a function | assign a function to a variable
207
python: In functional programming, your functions should not have
side effects
208
python: To create a lambda function, type
(lambda x: x*5)(2)
209
python: **my_dict converts {"key": "values"} to
"key" = "value"
210
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)
211
python: A closure must return
a pointer to an inner nested function (it is the name of the function with no parentheses)