Skip to content

Instantly share code, notes, and snippets.

@JoshHrach
Created April 9, 2020 01:14
Show Gist options
  • Save JoshHrach/3b99b42777259a53fc8ed71a8071224e to your computer and use it in GitHub Desktop.
Save JoshHrach/3b99b42777259a53fc8ed71a8071224e to your computer and use it in GitHub Desktop.
Sample Property Wrappers
@propertyWrapper
/// 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()
}
@propertyWrapper
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