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 trial

iOS Swift Basics (retired) Operators Unary Operators

weixin yang
weixin yang
312 Points

Guys I still dont get Unary operator

Guys I still dont get the Unary Operator can any explain it to me more about it.

1 Answer

Unary operators change a single number or target and return a value. The unary operators can be used as prefix operators or postfix operators. Some uses of unary operators are to identify positive numbers (+) negative (-) numbers and to increment(++) or decrement (--) a numeric value.
Here are some examples from the Swift Programming language documents:

Increment operator (++) and decrement operator (--) are shortcuts to increase or decrease the value of a numeric variable by 1.

Increment unary operator (++) var a=0 let b = ++a //a and b are now both equal to 1 due to ++ unary operator incrementing a by 1.

Decrement operator (--) var i = 10 --i // i = 9

If the unary operator is written BEFORE the variable it increments the variable BEFORE returning its value. If the operator is written AFTER the variable it increments the variable AFTER returning it's value. You can check out the Swift Programming language document of examples.

You can toggle the sign of the numeric value using the unary minus and plus operators.

Unary Minus Operator: let three = 3 let minusThree = -three //minusThree equals -3 let plusThree = -minusThree //plusThree equals 3, or "minus minus three"

The Unary Plus Operator doesn't actually do anything but it can provide symmetry in your code. The unary plus operator just returns the value it operates on. let minusSix = -6 let alsoMinusSix = +minusSix //alsoMinusSix equals -6