Skip to content

Instantly share code, notes, and snippets.

View mwaterfall's full-sized avatar

Michael Waterfall mwaterfall

View GitHub Profile
public protocol Changeable {}
extension Changeable {
/// Calls the `changes` closure passing the receiver value as an `inout` parameter. The final value of the argument
/// after the `changes` closure returns is then returned from this method. Benefits to using this function come
/// when used against value types.
///
/// Example:
///
/// extension UIEdgeInsets: Changeable {}
enum Material: String {
case wood, metal, glass, other
}
extension Material: Codable {}
extension Material: UnknownCaseRepresentable {
static let unknownCase: Material = .other
}
protocol UnknownCaseRepresentable: RawRepresentable, CaseIterable {
static var unknownCase: Self { get }
}
extension UnknownCaseRepresentable where Self.RawValue: Equatable {
init(rawValue: RawValue) {
let value = Self.allCases.first(where: { $0.rawValue == rawValue })
self = value ?? Self.unknownCase
}
}
extension Material {
init(from decoder: Decoder) throws {
self = try Material(from: decoder, default: .other)
}
}
extension RawRepresentable where RawValue: Decodable {
init(from decoder: Decoder, default: Self) throws {
let container = try decoder.singleValueContainer()
let rawValue = try container.decode(RawValue.self)
self = Self(rawValue: rawValue) ?? `default`
}
}
extension Material {
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let rawMaterial = try container.decode(String.self)
self = Material(rawValue: rawMaterial) ?? .other
}
}
enum Material: String, Codable {
case wood, metal, glass, other
}
imageView.apply(.logo)
imageView.apply(
.productImage(with: URL(string: "http://my-image-url")!),
loading: .loading,
failure: .failure
)
extension ImageDescriptor where ImageReference == UIImage {
static let logo = ImageDescriptor<UIImage>(
imageReference: UIImage(named: "logo")!.withRenderingMode(.alwaysTemplate),
properties: UIImageView.Properties(
contentMode: .center,
backgroundColor: .white,
tintColor: .lightGray,
accessibilityIdentifier: "logoImage"
)
)
extension UIImageView {
func apply(_ imageDescriptor: ImageDescriptor<UIImage>) {
cancelAnyExistingFetches()
accessibilityIdentifier = imageDescriptor.properties.accessibilityIdentifier
backgroundColor = imageDescriptor.properties.backgroundColor
contentMode = imageDescriptor.properties.contentMode
tintColor = imageDescriptor.properties.tintColor
image = imageDescriptor.imageReference
}