Skip to content

make Range and ClosedRange conditionally Codable #21755

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions stdlib/public/core/ClosedRange.swift
Original file line number Diff line number Diff line change
Expand Up @@ -456,3 +456,22 @@ extension ClosedRange {
// shorthand. TODO: Add documentation
public typealias CountableClosedRange<Bound: Strideable> = ClosedRange<Bound>
where Bound.Stride : SignedInteger

extension ClosedRange : Codable where Bound : Codable {
private enum CodingKeys : String, CodingKey {
case lowerBound = "lowerBound", upperBound = "upperBound"
}

public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let lowerBound = try container.decode(Bound.self, forKey: .lowerBound)
let upperBound = try container.decode(Bound.self, forKey: .upperBound)
self = lowerBound...upperBound
}

public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(lowerBound, forKey: .lowerBound)
try container.encode(upperBound, forKey: .upperBound)
}
}
19 changes: 19 additions & 0 deletions stdlib/public/core/Range.swift
Original file line number Diff line number Diff line change
Expand Up @@ -898,3 +898,22 @@ public typealias CountableRange<Bound: Strideable> = Range<Bound>
// shorthand. TODO: Add documentation
public typealias CountablePartialRangeFrom<Bound: Strideable> = PartialRangeFrom<Bound>
where Bound.Stride : SignedInteger

extension Range : Codable where Bound : Codable {
private enum CodingKeys : String, CodingKey {
case lowerBound = "lowerBound", upperBound = "upperBound"
}

public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let lowerBound = try container.decode(Bound.self, forKey: .lowerBound)
let upperBound = try container.decode(Bound.self, forKey: .upperBound)
self = lowerBound..<upperBound
}

public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(lowerBound, forKey: .lowerBound)
try container.encode(upperBound, forKey: .upperBound)
}
}