英文:
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,
- Enum also searching specific status by id as Set of struct did.
- 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,
- Memory Allocation of each Status
- Search value or case by Status Code
- 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,
- Enum also searching specific status by id as Set of struct did.
- 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,
- Memory Allocation of each Status
- Search value or case by Status Code
- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论