Skip to content

Instantly share code, notes, and snippets.

@artemnovichkov
Last active July 30, 2018 15:16
Show Gist options
  • Save artemnovichkov/f99096136c7c4eff72f6c880569467b9 to your computer and use it in GitHub Desktop.
Save artemnovichkov/f99096136c7c4eff72f6c880569467b9 to your computer and use it in GitHub Desktop.
Addition and subtraction operators for Swift Optionals
func +=<T>(lhs: inout T?, rhs: T) where T: SignedNumeric {
switch lhs {
case .none:
break
case .some(let value):
lhs = .some(value + rhs)
}
}
func -=<T>(lhs: inout T?, rhs: T) where T: SignedNumeric {
lhs += -rhs
}
var hours: Int? = 5
hours -= 2
print(hours) //Prints Optional(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment