乐闻世界logo
搜索文章和话题

What are the collection types in Swift? What are the differences and use cases for Array, Set, and Dictionary?

2月21日 15:05

What are the collection types in Swift? What are the differences and use cases for Array, Set, and Dictionary?

Swift provides three main collection types: Array (arrays), Set (sets), and Dictionary (dictionaries). Each collection type has its specific purpose and characteristics.

Array (Arrays):

  • Ordered collection
  • Can contain duplicate elements
  • Can access elements by index
  • Example:
    swift
    var numbers = [1, 2, 3, 4, 5] numbers.append(6) numbers[0] = 10 let first = numbers.first // Optional(10) let count = numbers.count // 6

Common Array Operations:

swift
var array = [1, 2, 3] // Add elements array.append(4) array.insert(0, at: 0) // Remove elements array.remove(at: 0) array.removeLast() // Find elements let index = array.firstIndex(of: 2) // Sort array.sort() let sorted = array.sorted() // Iterate for (index, element) in array.enumerated() { print("\(index): \(element)") }

Set (Sets):

  • Unordered collection
  • Cannot contain duplicate elements
  • Elements must be hashable
  • Example:
    swift
    var set: Set<Int> = [1, 2, 3, 4, 5] set.insert(6) set.contains(3) // true let count = set.count // 6

Common Set Operations:

swift
var set1: Set<Int> = [1, 2, 3, 4, 5] var set2: Set<Int> = [4, 5, 6, 7, 8] // Set operations let union = set1.union(set2) // {1, 2, 3, 4, 5, 6, 7, 8} let intersection = set1.intersection(set2) // {4, 5} let difference = set1.subtracting(set2) // {1, 2, 3} let symmetricDifference = set1.symmetricDifference(set2) // {1, 2, 3, 6, 7, 8} // Check relationships set1.isSubset(of: set2) // false set1.isSuperset(of: set2) // false set1.isDisjoint(with: set2) // false // Add and remove set1.insert(6) set1.remove(1)

Dictionary (Dictionaries):

  • Unordered key-value pair collection
  • Keys must be unique
  • Keys must be hashable
  • Example:
    swift
    var dict = ["name": "John", "age": "30"] dict["email"] = "john@example.com" dict["name"] = "Jane" let name = dict["name"] // Optional("Jane") let count = dict.count // 3

Common Dictionary Operations:

swift
var dict = ["name": "John", "age": "30"] // Add and update dict["email"] = "john@example.com" dict.updateValue("Jane", forKey: "name") // Remove dict.removeValue(forKey: "age") // Access if let name = dict["name"] { print(name) } // Iterate for (key, value) in dict { print("\(key): \(value)") } // Get all keys and values let keys = Array(dict.keys) let values = Array(dict.values)

Differences Between Array, Set, and Dictionary:

  1. Order:

    • Array: ordered
    • Set: unordered
    • Dictionary: unordered (key-value pairs)
  2. Duplicate Elements:

    • Array: can contain duplicate elements
    • Set: cannot contain duplicate elements
    • Dictionary: keys must be unique, values can be duplicated
  3. Access Method:

    • Array: access by index
    • Set: access by membership check
    • Dictionary: access by key
  4. Performance:

    • Array: insertion and deletion O(n), access O(1)
    • Set: insertion, deletion, lookup O(1)
    • Dictionary: insertion, deletion, lookup O(1)

Use Cases:

  1. When to Use Array:

    • Need to maintain element order
    • Allow duplicate elements
    • Need to access elements by index
    • Examples: to-do list, history log
  2. When to Use Set:

    • Need to ensure element uniqueness
    • Need to quickly check if element exists
    • Need set operations (union, intersection, etc.)
    • Examples: tags, user ID sets
  3. When to Use Dictionary:

    • Need to quickly look up values by key
    • Need to store key-value pair data
    • Keys are unique
    • Examples: user information, configuration options

Best Practices:

  1. Choose appropriate collection type based on requirements
  2. Use Array to maintain order
  3. Use Set to ensure uniqueness
  4. Use Dictionary to store key-value pairs
  5. Be aware of collection performance characteristics
标签:Swift