Skip to content

Instantly share code, notes, and snippets.

@cyrilchandelier
Last active September 19, 2019 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyrilchandelier/48766247bcc69f60a8f09051d1b0d243 to your computer and use it in GitHub Desktop.
Save cyrilchandelier/48766247bcc69f60a8f09051d1b0d243 to your computer and use it in GitHub Desktop.
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