Swift Sets Flashcards
Gain a comprehensive understanding of how to work with the properties and methods of Sets in swift to improve ability to successfully complete toy problems.
What does an “array” do?
Stores values of the same type in an ordered list.
What does a “set” do?
It stores distinct values of the same type in a collection with no defined ordering.
When is a good time to use a “set” instead of an array? (List two examples)
- When the order of items is not important
2. When you need to ensure that an item appears only once.
- What is a hash value?
2. Provide an example
- An Int value that is the same for all objects that compare equally.
- (EX.) - if a == b, the hash value of a is equal to the hash value of b
A type must be _____ in order to be stored in a set.
hashable (The type must provide a way to compute a “hash value” for itself)
What Swift types are hashable by default? (List 2)
- All of Swift’s basic types such as String, Int, Double, and Bool.
- Enumeration case values without associated values.
Data types that are hashable can be used as 1. ____ or 2. ______.
- Set value types
2. Dictionary key types.
Create an empty set of a certain type using the initializer syntax
var setName = Set( )
Initialize a set with an array literal
var arrayLiteralSet: Set = [“ItemOne”, “ItemTwo”, “ItemThree”]
Initialize a set with an array literal using Swift’s type inference to assume the type
var arrayLiteralSet: Set = ["ItemOne", "ItemTwo", "ItemThree"] //Because all values are same type swift can infer that Set is correct.
You access and modify a set through it’s 1)_____ and 2)_____.
- Methods
2. Properties
You can add a new item into a set by calling the set’s ______ method.
insert(_: )
You can check whether a sets count property is equal to 0 by using the ___ property.
isEmpty
Use isEmpty in an if statement
if setName.isEmpty { instructions if true } else { instructions if false }
You can remove an item from a set by calling the set’s _____ method
remove(_: )