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

In Swift enumerations, what’s the difference between raw values and associated values?

Câu trả lời

In Swift enumerations, raw values and associated values serve different purposes and have distinct characteristics.

Raw Values

Raw values are predefined constant values assigned to each case of an enumeration. These values are set at compile time and must be of the same type for all cases within the enumeration. The types that can be used for raw values include integers, strings, characters, or any other literal-convertible types. Raw values are useful when you need a fixed, identifiable value for each case, which can be used for comparison or serialization.

Example:

enum Direction: Int {
    case north = 1
    case south = 2
    case east = 3
    case west = 4
}

let direction = Direction.south
print(direction.rawValue) // Output: 2

In this example, each case of the Direction enum is assigned a unique integer raw value.

Associated Values

Associated values, on the other hand, allow each case of an enumeration to store additional information of varying types. These values are specified when you create an instance of the enumeration and can differ for each case. Associated values make enums more flexible and capable of representing more complex data structures.

Example:

enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}

let productBarcode = Barcode.upc(8, 85909, 51226, 3)
let qrCode = Barcode.qrCode("ABCDEFGHIJKLMNOP")

In this example, the Barcode enum has two cases: upc with a tuple of four integers as its associated value, and qrCode with a string as its associated value.

Key Differences

  1. Type Consistency:

    • Raw Values: All cases must have the same type of raw value.
    • Associated Values: Each case can have different types of associated values.
  2. Initialization:

    • Raw Values: You can initialize an enum case from its raw value using the init?(rawValue:) initializer, which returns an optional because the raw value might not match any case.
    • Associated Values: You initialize an enum case with its associated values directly when creating an instance.
  3. Usage:

    • Raw Values: Useful for simple, fixed values that need to be comparable or serializable.
    • Associated Values: Useful for cas...
middle

middle

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

expert

What’s the difference between init?() and init() ?

senior

Can you rewrite this code using mutating function?

expert

What is the use of Hashable protocol?

Bình luận

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

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