Câu hỏi phỏng vấn Swift
Câu hỏi

What's the main difference between the Array , Set and Dictionary collection
type?

Câu trả lời

In Swift, Arrays, Sets, and Dictionaries are the primary collection types, each serving distinct purposes and having unique characteristics. Here’s a detailed comparison of these three collection types:

Arrays

  • Ordered Collection: Arrays store elements in a specific order, and each element can be accessed by its index.
  • Duplicates Allowed: Arrays can contain multiple instances of the same value.
  • Index-Based Access: Elements in an array can be accessed using their index.
  • Initialization: Arrays are initialized using square brackets, e.g., var arrayExample: [Int] = [1][2][3][4][5][1][3][4].

Example:

swift Copy
var arrayExample: [Int] = [1, 2, 3, 4, 5]
arrayExample.append(6) // Adds 6 to the end of the array
arrayExample.remove(at: 0) // Removes the first element

Sets

  • Unordered Collection: Sets store elements without any specific order.
  • Unique Elements: Sets do not allow duplicate elements; each element must be unique.
  • No Index-Based Access: Elements in a set cannot be accessed by an index.
  • Initialization: Sets are initialized using square brackets with the Set type, e.g., var setExample: Set<Int> = [1][2][3][4][5][1][3][4].

Example:

swift Copy
var setExample: Set<Int> = [1, 2, 3, 4, 5]
setExample.insert(6) // Adds 6 to the set
setExample.remove(1) // Removes 1 from the set

Dictionaries

  • Key-Value Pairs: Dictionaries store associations between unique keys and values.
  • Unordered Collection: The order of key-value pairs is not maintained.
  • Unique Keys: Each key in a dictionary must be unique, but values can be duplicated.
  • Initialization: Dictionaries are initialized using square brackets with key-value pairs, e.g., var dictionaryExample: [String: Int] = ["one": 1, "two": 2, "three": 3][1][4][6].

Example:

swift Copy
var dictionaryExample: [String: Int] = ["one": 1, "two": 2, "three": 3]
dictionaryExample["four"] = 4 // Adds a new key-value pair
dictionaryExample["one"] = nil // Removes the key-value pair with key "one"

Performance Considerations

  • Arrays: Best used whe...
middle

middle

Gợi ý câu hỏi phỏng vấn

senior

What is Copy on Write (Cow) in Swift?

senior

When should you use Structs over Classes?

senior

When is it safe to use an unowned reference?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào