Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A Swift operator to only assign a value when the right operand is not nil
import Foundation
precedencegroup OptionalAssignment {
associativity: right
infix operator ?=: OptionalAssignment
public func ?= <T>(variable: inout T, value: T?) {
if let unwrapped = unwrap(any: value) ?? nil {
variable = unwrapped
public func unwrap<T: Any>(any: T) -> T? {
let mirror = Mirror(reflecting: any)
guard mirror.displayStyle == .optional else { return any }
guard let child = mirror.children.first else { return nil }
return unwrap(any: child.value) as? T
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment