Swift Collections

Swift Collections

Use arrays, dictionaries, and sets to store ordered lists, key-value pairs, and unique items.


Arrays

Arrays store ordered lists of values.

Syntax: [Type] for type, append with .append, count with .count, access with array[index].

Example

var nums: [Int] = [1, 2, 3]
nums.append(4)
print(nums.count)    // 4
print(nums[0])       // 1

This example creates an [Int] array, appends a value, reads the count, and accesses the first element.


Dictionaries

Dictionaries store key-value pairs.

Syntax: [Key: Value] for type, assign with dict[key] = value, read with dict[key] ?? default.

Example

var ages: [String: Int] = ["Kai": 30]
ages["Elisabeth"] = 25
print(ages["Kai"] ?? 0)

This example defines a [String: Int] dictionary, inserts a key, and reads with nil-coalescing.



Sets

Sets store unique items.

Syntax: Set<Element> or literal, test membership with .contains.

Example

var letters: Set<Character> = ["a", "b", "a"]
print(letters.contains("a"))

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *