Hai Huang12,675 Points
Why are the unary operators unary operators?
(Maybe the title is a little stupid..)
I completely understand the usages of the unary operators introduced in this video, but some of them seem to me binary operators.
Let's say for an example.
var a: Int = 1
a += 1 a -= 1
In the two lines above, both "+=" and "-=" seem to me binary operators because they connect two operands (a and 1) and are located in between as infix.
Well, the negating operator (var a: Bool = true; a = !a) is for me a unary operator because it only affects one operand (a).
Michael HuletTreehouse Moderator 47,742 Points
Your concept of unary and binary operators is correct. I don't know why the mathematical assignment operators were listed as unary operators in this video, because they're actually binary operators, as you suspected. There are only 3 unary operators in Swift by default:
- The logical negation operator (
!). This inverts a boolean expression, so
- The mathematical negation operator (
-). This makes a positive number negative, and a negative number positive (example:
- The unary plus operator (
+). This simply returns its value as is. For example
+42is still just
42. This operator is entirely useless, but looks nice near a mathematical negation operator when you're choosing if you want something positive or negative