Enum vs Struct在Swift中的特定情况下。

huangapple go评论65阅读模式
英文:

Enum vs Struct with certain scenario in Swift

问题

以下是您要翻译的内容:

I've Enum and Struct below implemented with HTTPStatus to demonstrate the example. I like to know about for finding specific Status and reading the properties which one is more performant on read and also memory efficient?

What I've noticed is exclude code style, length,

  1. Enum also searching specific status by id as Set of struct did.
  2. Enum uses Switch case to read properties of specific case even after we've stand along HTTPStatus while struct doesn't.

Enum:

enum HTTPStatus: UInt16 {
    
    case ok = 200
    case created = 201
    case accepted = 202
    
    var label: String {
        
        switch self {
        case .ok:
            return "Ok"
        case .created:
            return "Created"
        case .accepted:
            return "Accepted"
        }
    }
    
    var description: String {
        
        switch self {
        case .ok:
            return "\(self.rawValue) - \(self.label) is a standard response for successful HTTP requests. The actual response will depend on the request method used. In a GET request, the response will contain an entity corresponding to the requested resource. In a POST request, the response will contain an entity describing or containing the result of the action."
        case .created:
            return "\(self.rawValue) - \(self.label) means the request has been fulfilled, resulting in the creation of a new resource."
        case .accepted:
            return "\(self.rawValue) - \(self.label) means the request has been accepted for processing, but the processing has not been completed. The request might or might not be eventually acted upon, and may be disallowed when processing occurs."
        }
    }
    
    var error: ErrorType {
        
        switch self.rawValue {
            
        case 200...299: return .none
            
        default: return .server
        }
    }
    
    enum ErrorType: UInt8 {
        
        case server
        case client
        case none
    }
}

let statusCode: UInt16 = 500

if let status = HTTPStatus(rawValue: statusCode) {
    
    print(status.description)
}

Struct:


struct HTTPStatus: Equatable, Hashable {
    
    let code: UInt16
    let shortLabel: String
    
    private let longLabel: String
    
    init(_ code: UInt16, shortLabel: String, longLabel: String) {
        
        self.code = code
        self.shortLabel = shortLabel
        self.longLabel = longLabel
    }
    
    var description: String {
        
        return "\(self.code) - \(self.shortLabel) \(self.longLabel)"
    }
    
    func hash(into hasher: inout Hasher) {
        
        hasher.combine(self.code)
    }
    
    var isSuccess: Bool { return self.code < 300}
    
    var isClientError: Bool { return self.code > 399}

    var isServerError: Bool { return self.code > 499}
}

let httpStatuses: Set<HTTPStatus> = [

    .init(200, shortLabel: "Ok", longLabel: "is a standard response for successful HTTP requests. The actual response will depend on the request method used. In a GET request, the response will contain an entity corresponding to the requested resource. In a POST request, the response will contain an entity describing or containing the result of the action.")
]

let statusCode: UInt16 = 500

if let status = httpStatuses.first(where: {$0.code == statusCode}) {
    
    print(status.description)
}

Assume that we've to implement all HTTPStatusCode in both enum and structs. In this scenario which one more performant in terms of,

  1. Memory Allocation of each Status
  2. Search value or case by Status Code
  3. Time on Reading properties and allocation of memory for that property value on Enum vs Struct?

Overall I just want to find out whether I need enum or not.

英文:

I've Enum and Struct below implemented with HTTPStatus to demonstrate the example. I like to know about for finding specific Status and reading the properties which one is more performant on read and also memory efficient?

What I've noticed is exclude code style, length,

  1. Enum also searching specific status by id as Set of struct did.
  2. Enum uses Switch case to read properties of specific case even after we've stand along HTTPStatus while struct doesn't.

Enum:

enum HTTPStatus: UInt16 {
    
    case ok = 200
    case created = 201
    case accepted = 202
    
    var label: String {
        
        switch self {
        case .ok:
            return &quot;Ok&quot;
        case .created:
            return &quot;Created&quot;
        case .accepted:
            return &quot;Accepted&quot;
        }
    }
    
    var description: String {
        
        switch self {
        case .ok:
            return &quot;\(self.rawValue) - \(self.label) is a standard response for successful HTTP requests. The actual response will depend on the request method used. In a GET request, the response will contain an entity corresponding to the requested resource. In a POST request, the response will contain an entity describing or containing the result of the action.&quot;
        case .created:
            return &quot;\(self.rawValue) - \(self.label) means the request has been fulfilled, resulting in the creation of a new resource.&quot;
        case .accepted:
            return &quot;\(self.rawValue) - \(self.label) means the request has been accepted for processing, but the processing has not been completed. The request might or might not be eventually acted upon, and may be disallowed when processing occurs.&quot;
        }
    }
    
    var error: ErrorType {
        
        switch self.rawValue {
            
        case 200...299: return .none
            
        default: return .server
        }
    }
    
    enum ErrorType: UInt8 {
        
        case server
        case client
        case none
    }
}

let statusCode: UInt16 = 500

if let status = HTTPStatus(rawValue: statusCode) {
    
    print(status.description)
}

Struct:


struct HTTPStatus: Equatable, Hashable {
    
    let code: UInt16
    let shortLabel: String
    
    private let longLabel: String
    
    init(_ code: UInt16, shortLabel: String, longLabel: String) {
        
        self.code = code
        self.shortLabel = shortLabel
        self.longLabel = longLabel
    }
    
    var description: String {
        
        return &quot;\(self.code) - \(self.shortLabel) \(self.longLabel)&quot;
    }
    
    func hash(into hasher: inout Hasher) {
        
        hasher.combine(self.code)
    }
    
    var isSuccess: Bool { return self.code &lt; 300}
    
    var isClientError: Bool { return self.code &gt; 399}

    var isServerError: Bool { return self.code &gt; 499}
}

let httpStatuses: Set&lt;HTTPStatus&gt; = [

    .init(200, shortLabel: &quot;Ok&quot;, longLabel: &quot;is a standard response for successful HTTP requests. The actual response will depend on the request method used. In a GET request, the response will contain an entity corresponding to the requested resource. In a POST request, the response will contain an entity describing or containing the result of the action.&quot;)
]

let statusCode: UInt16 = 500

if let status = httpStatuses.first(where: {$0.code == statusCode}) {
    
    print(status.description)
}

Assume that we've to implement all HTTPStatusCode in both enum and structs. In this scenario which one more performant in terms of,

  1. Memory Allocation of each Status
  2. Search value or case by Status Code
  3. Time on Reading properties and allocation of memory for that property value on Enum vs Struct?

Overall I just want to find out wether I need enum or not.

答案1

得分: 0

Swift 枚举是值类型,就像结构体一样。除非放在某种堆分配的缓冲区中(比如数组),它们是栈分配的。无论是枚举还是结构体,都不会有自动内存管理的额外开销。在性能方面,它们应该是可比较的。

总的来说,我只是想找出是否需要使用枚举。

您的对象是否表示一组离散的状态?使用枚举。它是否是给定类型的任意值的容器?使用结构体。

英文:

Swift enums are value types, just like structs. Unless put in some kind of heap-allocated buffer (like an array), they are stack allocated. You don't get the overhead from automatic memory management with either enums or structs. In terms of performance, they should be comparable.

> Overall I just want to find out wether I need enum or not.

Does your object represent a discrete set of states? Use enums. Is it a container for arbitrary values of the given types? Use a struct.

huangapple
  • 本文由 发表于 2023年6月9日 09:43:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76436686.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定