Skip to content

Instantly share code, notes, and snippets.

Created April 9, 2020 01:14
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Sample Property Wrappers
/// Wrapper used to easily encode a `Date` to and decode a `Date` from an ISO 8601 formatted date string.
struct ISO8601Date: Codable {
var wrappedValue: Date
init(wrappedValue: Date) {
self.wrappedValue = wrappedValue
init(from decoder: Decoder) throws {
let value = try decoder.singleValueContainer()
let stringValue = try value.decode(String.self)
if let date = ISO8601DateFormatter().date(from: stringValue) {
wrappedValue = date
} else {
throw DecodingError.typeMismatch(Date.self, DecodingError.Context(codingPath: [], debugDescription: "Failed to decode ISO Date. Invalid string format."))
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
let string = ISO8601DateFormatter().string(from: wrappedValue)
try container.encode(string)
struct DateTest: Codable {
@ISO8601Date var date: Date = Date()
struct UserDefault<StoredType> {
public let key: String
public let defaultValue: StoredType
var wrappedValue: StoredType {
get {
UserDefaults.standard.object(forKey: key) as? StoredType ?? defaultValue
set {
UserDefaults.standard.set(newValue, forKey: key)
class SettingManager {
@UserDefault(key: "userViewedWhatsNew", defaultValue: false) static var userViewedWhatsNew: Bool
@UserDefault(key: "lastLoggedInUser", defaultValue: nil) static var lastLoggedInUser: String?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment