-
Notifications
You must be signed in to change notification settings - Fork 317
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
New
@NonEmptyStringDecodable
(#2819)
This allows decorating a `String` property in a `Decodable` type so it ensures it gets converted to `nil` if it's empty. It will be used for `PaywallData`.
- Loading branch information
Showing
3 changed files
with
97 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
// | ||
// Copyright RevenueCat Inc. All Rights Reserved. | ||
// | ||
// Licensed under the MIT License (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// https://opensource.org/licenses/MIT | ||
// | ||
// NonEmptyStringDecodable.swift | ||
// | ||
// Created by Nacho Soto on 7/14/23. | ||
|
||
import Foundation | ||
|
||
/// A property wrapper that ensures decoded strings aren't empty | ||
/// - Example: | ||
/// ``` | ||
/// struct Data { | ||
/// @NonEmptyStringDecodable var value: String? // becomes `nil` if value is empty or has only whitespaces | ||
/// } | ||
/// ``` | ||
@propertyWrapper | ||
struct NonEmptyStringDecodable { | ||
|
||
var wrappedValue: String? | ||
|
||
} | ||
|
||
extension NonEmptyStringDecodable: Equatable, Hashable {} | ||
|
||
extension NonEmptyStringDecodable: Decodable { | ||
|
||
init(from decoder: Decoder) throws { | ||
let container = try decoder.singleValueContainer() | ||
self.wrappedValue = try container.decode(String?.self)?.notEmptyOrWhitespaces | ||
} | ||
|
||
} | ||
|
||
extension NonEmptyStringDecodable: Encodable { | ||
|
||
func encode(to encoder: Encoder) throws { | ||
var container = encoder.singleValueContainer() | ||
try container.encode(self.wrappedValue) | ||
} | ||
|
||
} | ||
|
||
extension KeyedDecodingContainer { | ||
|
||
func decode( | ||
_ type: NonEmptyStringDecodable.Type, | ||
forKey key: Key | ||
) throws -> NonEmptyStringDecodable { | ||
return try self.decodeIfPresent(type, forKey: key) ?? .init() | ||
} | ||
|
||
} |
This file contains 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