Swift Flashcards
When to use a For loop or While loop?
For loop: when you know the number of iterations ahead of time.
While loop: when you don’t know the number of iterations ahead of time
== VS ===
== tests for the Equatable protocol. ie does “abc” equal “abc”
=== tests for address matching. Do two instances of an object have the same address?
break vs return
Break: will exit loop or switch
Return: will exit the function
What’s the syntax for replacing an element in an array with another element?
array[x] = y
What’s the syntax for assigning a value to a dictionary?
dictionary[x] = y
How do you check if a dictionary contains a value?
- dict.keys.contains(key)
- if let value = dict[key]
- if dict[key] != nil
How do you determine how many times you want to repeat an operation?
First ask: What data do i need to see? all of it? some of it?
start from base case and develop from there. Consider writing out options.
How to iterate both index and value of an array?
for (index, value) in array.enumerated()
How to iterate elements of a dictionary?
for (key, value) in dictionary
How to cast from Int to String?
Int(string)
returns optional
How to cast from string to array?
Array(string)
How would you instantiate the absolute minimum as an Integer?
Int.min
How would you instantiate the absolute max as an Integer?
Int.max
How to return the greater of two values?
max(x,y)
How to return the lesser of two values?
min(x,y)
How to return a lowercase version of string?
string.lowercased()
this returns a new object!
How would you break a sentence into an array of strings?
string.components(seperatedBy: “ “)
How to return the prefix of an array?
array.prefix(count)
How to join an array of strings?
array.joined(separator: “”)
How to remove and return an element in an array?
array.remove(at: index)
Are swift parameters passed in as variables or constants?
Constants
What does inout do?
Allows you to modify an object in place, instead of returning a new object
What syntax do you use to pass an argument as inout?
- func test(inout string: String)
- test(string: &string)
How would you insert an element in an array?
array.insert(value, at: index)
How to clean a string of non alpha characters?
string.filter { $0.isLetter }
How to convert a string to an array?
let array = Array(string)
What does the type Int32 do?
It stores an integer with a length of 32 bits. This is different than the Int type which stores the default system value, which could be 32 or 64.
How to join an array of strings?
let result = array.joined(separator: “”)
What is the inout syntax for a func signature?
ie func reverseString(string: inout String)
What is the syntax for getting the first N elements of an array?
array.prefix(n)
How would you sort an array of this type? [[Int: Int]]
array.sort { $0.values.first! < $1.values.first! }
What is the diff between Sort, Sorted, and Sorted(by: )
Sort: called in place
Sorted: returns a copy
Sorted(by: ): returns a copy, accepts >
or <
as an argument