Understanding Miscellaneous Operators
Introduction to Miscellaneous Operators
Swift supports various types of operators, including arithmetic, comparison, logical, bitwise, assignment, and range operators. In addition to these, Swift provides several miscellaneous operators that enhance the language's flexibility and functionality.
Types of Miscellaneous Operators in Swift
Name | Operator | Example |
---|---|---|
Unary Minus | - | -23 |
Unary Plus | + | +32 |
Ternary Conditional | ? : | X > Y ? 43 : 21 |
Unary Minus Operator in Swift
The unary minus (-) operator is used to change the sign of a numeric value. It converts a positive number into a negative and vice versa. It is a prefix operator, meaning it is placed before the operand without any space.
Syntax:
-x
Example: Using Unary Minus Operator in Swift
import
Foundation
let a
= 50
let b
= -10
// Using unary minus operator
let result
= a
+ (-b)
// 50 + 10
print("Sum of \(a) and -
\(b) =
\(result)")
Output
Unary Plus Operator in Swift
The unary plus (+) operator ensures a numeric expression remains positive. However, it does not alter the actual value of the number. Like the unary minus operator, it is also a prefix operator.
Syntax:
+x
Example: Using Unary Plus Operator in Swift
import
Foundation
let a
= 15
let b
= +5
// Using unary plus operator
let sum
= a
+ b
// 15 + 5
print("Sum of \(a) and
\(b) =
\(sum)")
Output
Ternary Conditional Operator in Swift
The ternary conditional operator (condition ? expression1 : expression2
) is a shorthand for an if-else statement. It efficiently selects
one of two expressions based on a condition's truth value.
Syntax:
condition ? expression1 : expression2
Example: Using Ternary Conditional Operator in Swift
import
Foundation
let x
= 10
let y
= 20
// Using ternary conditional operator
let maxNumber
= x
> y
? x
: y
print("The larger number between \(x) and
\(y) is
\(maxNumber)")