Last active
September 19, 2019 06:09
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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