Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHai Huang
12,675 PointsWhy 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).
1 Answer
Michael Hulet
47,913 PointsYour 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!true
isfalse
, and!false
istrue
- The mathematical negation operator (
-
). This makes a positive number negative, and a negative number positive (example:-42
) - The unary plus operator (
+
). This simply returns its value as is. For example+42
is still just42
. This operator is entirely useless, but looks nice near a mathematical negation operator when you're choosing if you want something positive or negative