Created
December 4, 2024 10:06
-
-
Save brunogama/5788ca33bed0d90863c0730af53279bd to your computer and use it in GitHub Desktop.
Conformed Box
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final class Box<Type> { | |
var value: Type | |
init(_ value: Type) { | |
self.value = value | |
} | |
} | |
extension Box: CustomStringConvertible where Type: CustomStringConvertible { | |
var description: String { | |
value.description | |
} | |
} | |
extension Box: Equatable where Type: Equatable { | |
static func ==(lhs: Box, rhs: Box) -> Bool { | |
lhs.value == rhs.value | |
} | |
} | |
extension Box: Comparable where Type: Comparable { | |
static func <(lhs: Box, rhs: Box) -> Bool { | |
lhs.value < rhs.value | |
} | |
} | |
extension Box: Hashable where Type: Hashable { | |
func hash(into hasher: inout Hasher) { | |
hasher.combine(value) | |
} | |
} | |
extension Box: Identifiable where Type: Identifiable { | |
var id: Type.ID { value.id } | |
} | |
func map<Other>(_ function: (Type) throws -> Other) rethrows -> Box<Other> { | |
Box<Other>(try function(value)) | |
} | |
extension Box: Encodable where Type: Encodable { | |
func encode(to encoder: Encoder) throws { | |
var container = encoder.singleValueContainer() | |
try container.encode(value) | |
} | |
} | |
extension Box: Decodable where Type: Decodable { | |
convenience init(from decoder: Decoder) throws { | |
let container = try decoder.singleValueContainer() | |
let value = try container.decode(Type.self) | |
self.init(value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment