0% found this document useful (0 votes)
8 views6 pages

Aaaf

Uploaded by

iremercan912
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views6 pages

Aaaf

Uploaded by

iremercan912
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

1/23/24, 8:00 PM Learn Swift: Arrays & Sets Cheatsheet | Codecademy

Cheatsheets / Learn Swift

Arrays & Sets

Array

An array stores an ordered collection of values of the var scores = [Int]()


same data type.
Use the initializer syntax, [Type]() , to create an
empty array of a certain type. // The array is empty: []

Initialize with Array Literal

An array can be initialized with an array literal, which is // Using type inference:
a short-hand method of writing one or more values as
an array collection.
var snowfall = [2.4, 3.6, 3.4, 1.8, 0.0]
An array literal is written as a list of values, separated by
commas, and surrounded by a pair of square brackets. // Being explicit with the type:
var temp: [Int] = [33, 31, 30, 38, 44]

Index

An index refers to an item’s position within an ordered var vowels = ["a", "e", "i", "o", "u"]
list. Use the subscript syntax, array[index] , to
retrieve an individual element from an array.
Note: Swift arrays are zero-indexed, meaning the first print(vowels[0]) // Prints: a
element has index 0. print(vowels[1]) // Prints: e
print(vowels[2]) // Prints: i
print(vowels[3]) // Prints: o
print(vowels[4]) // Prints: u

.count Property

The .count property returns the number of var grocery = [" 🥓 ", "🥞 ", "🍪 ", "🥛 ",
elements in an array.
" 🍊 "]
print(grocery.count)

// Prints: 5
https://www.codecademy.com/learn/learn-swift/modules/learn-swift-arrays/cheatsheet 1/6
1/23/24, 8:00 PM Learn Swift: Arrays & Sets Cheatsheet | Codecademy

.append() Method and += Operator

The .append() method can be called on an array var gymBadges = ["Boulder", "Cascade"]
to add an item to the end of the array.
The += addition assignment operator can be used to
add the elements of another array to the existing array. gymBadges.append("Thunder")
gymBadges += ["Rainbow", "Soul"]

// ["Boulder", "Cascade", "Thunder",


"Rainbow", "Soul"]

.insert() and .remove() Methods

The .insert() method can be called on an array var moon = [" 🌖 ", "🌗 ", "🌘 ", "🌑 "]
to add an element at a specified index. It takes two
arguments: value and at: index .
The .remove() method can be called on an array
moon.insert(" 🌕 ", at: 0)
to remove an element at a specified index. It takes one
argument: at: index . // [" 🌕 ", "🌖 ", "🌗 ", "🌘 ", "🌑 "]
moon.remove(at: 4)

// [" 🌕 ", "🌖 ", "🌗 ", "🌘 "]

Iterating Over an Array

In Swift, a for - in loop can be used to iterate var employees = ["Michael", "Dwight",
through the items of an array.
"Jim", "Pam", "Andy"]
This is a powerful tool for working with and
manipulating a large amount of data.
for person in employees {
print(person)
}

// Prints: Michael
// Prints: Dwight
// Prints: Jim
// Prints: Pam
// Prints: Andy

https://www.codecademy.com/learn/learn-swift/modules/learn-swift-arrays/cheatsheet 2/6
1/23/24, 8:00 PM Learn Swift: Arrays & Sets Cheatsheet | Codecademy

Swift Sets

We can use a set to store unique elements of the same var paintingsInMOMA: Set = ["The Dream",
data type.
"The Starry Night", "The False Mirror"]

Empty Sets

An empty set is a set that contains no values inside of it. var team = Set<String>()

print(team)
// Prints: []

Populated Sets

To create a set populated with values, use the Set var vowels: Set = ["a", "e", "i", "o",
keyword before the assignment operator.
"u"]
The values of the set must be contained within brackets
[] and separated with commas , .

.insert()

To insert a single value into a set, append var cookieJar: Set = ["Chocolate Chip",
.insert() to a set and place the new value inside
"Oatmeal Raisin"]
the parentheses () .

// Add a new element


cookieJar.insert("Peanut Butter Chip")

https://www.codecademy.com/learn/learn-swift/modules/learn-swift-arrays/cheatsheet 3/6
1/23/24, 8:00 PM Learn Swift: Arrays & Sets Cheatsheet | Codecademy

.remove() and .removeAll() Methods

To remove a single value from a set, append var oddNumbers: Set = [1, 2, 3, 5]
.remove() to a set with the value to be removed
placed inside the parentheses () .
To remove every single value from a set at once, // Remove an existing element
append .removeAll() to a set. oddNumbers.remove(2)

// Remove all elements


oddNumbers.removeAll()

.contains()

Appending .contains() to an existing set with an var names: Set = ["Rosa", "Doug",
item in the parentheses () will return a true or
"Waldo"]
false value that states whether the item exists
within the set.
print(names.contains("Lola")) // Prints:
false

if names.contains("Waldo"){
print("There's Waldo!")
} else {
print("Where's Waldo?")
}
// Prints: There's Waldo!

Iterating Over a Set

A for - in loop can be used to iterate over each var recipe: Set = ["Chocolate chips",
item in a set.
"Eggs", "Flour", "Sugar"]

for ingredient in recipe {


print ("Include \(ingredient) in the
recipe.")
}

https://www.codecademy.com/learn/learn-swift/modules/learn-swift-arrays/cheatsheet 4/6
1/23/24, 8:00 PM Learn Swift: Arrays & Sets Cheatsheet | Codecademy

.isEmpty Property

Use the built-in property .isEmpty to check if a var emptySet = Set<String>()


set has no values contained in it.

print(emptySet.isEmpty) // Prints: true

var populatedSet: Set = [1, 2, 3]

print(populatedSet.isEmpty) // Prints:
false

.count Property

The property .count returns the number of var band: Set = ["Guitar", "Bass",
elements contained within a set.
"Drums", "Vocals"]

print("There are \(band.count) players in


the band.")
// Prints: There are 4 players in the
band.

.intersection() Operation

The .intersection() operation populates a var setA: Set = ["A", "B", "C", "D"]
new set of elements with the overlapping elements of
var setB: Set = ["C", "D", "E", "F"]
two sets.

var setC = setA.intersection(setB)


print(setC) // Prints: ["D", "C"]

.union() Operation

The .union() operation populates a new set by var setA: Set = ["A", "B", "C", "D"]
taking all the values from two sets and combining them.
var setB: Set = ["C", "D", "E", "F"]

var setC = setA.union(setB)


print(setC)
// Prints: ["B", "A", "D", "F", "C", "E"]

https://www.codecademy.com/learn/learn-swift/modules/learn-swift-arrays/cheatsheet 5/6
1/23/24, 8:00 PM Learn Swift: Arrays & Sets Cheatsheet | Codecademy

.symmetricDifference() Operation

The .symmetricDifference() operation var setA: Set = ["A", "B", "C", "D"]
creates a new set with all the non-overlapping values
var setB: Set = ["C", "D", "E", "F"]
between two sets.

var setC = setA.symmetricDifference(setB)


print(setC)
// Prints: ["B", "E", "F", "A"]

.subtracting() Operation

The .subtracting() operation removes the var setA: Set = ["A", "B", "C", "D"]
values of one second set from another set and stores
var setB: Set = ["C", "D"]
the remaining values in a new set.

var setC = setA.subtracting(setB)


print(setC)
// Prints: ["B", "A"]

Print Share

https://www.codecademy.com/learn/learn-swift/modules/learn-swift-arrays/cheatsheet 6/6

You might also like