Swift – Misc Operators


Swift – Misc Operators



”;


Miscellaneous Operators Swift

Swift supports different types of operators like arithmetic, comparison, logical, bitwise, assignment and range operators. Apart from these operators it has miscellaneous operators are they are −






Operator Name Example
Unary Minus -23
+ Unary Plus 32
Condition ? X : Y Ternary operator X>Y ? 43 : 21= 43

Unary Minus Operator in Swift

A unary minus operator is used to represent a negative(-) sign that is placed before the numeric value. It converts a positive number into a negative and a negative number into a positive. It is a prefix operator, which means it is placed before the value without any white space.

Syntax

Following is the syntax of the unary minus operator −


-x

Example

Swift program to find the sum of two numbers using the unary minus operator.


import Foundation

let x = 23

// Specifying sign using unary minus operator
let y = -2
var sum = 0
sum = x + y // 23 + (-2)
print("Sum of (x) and (y) = (sum)")

Output


Sum of 23 and -2 = 21

Unary Plus Operator in Swift

A unary plus operator is used to make a numeric expression positive. It only adds a positive (+) sign before the numeric value but does not change the value. It is also a prefix operator.

Syntax

Following is the syntax of the unary plus operator −


+x

Example

Swift program to find the sum of two numbers using the unary plus operator.


import Foundation

let x = 20

// Specifying sign using unary plus operator
let y = +2
var sum = 0
sum = x + y // 23 + (+2)
print("Sum of (x) and (y) = (sum)")

Output


Sum of 20 and 2 = 22

Ternary Conditional Operator in Swift

A ternary conditional operator is a shorthand of an if-else statement. It has three parts: condition ? expression1 : espression2. It is the most effective way to decide between two expressions.

Because it evaluates one of the two given expressions according to whether the given condition is true or false. If the given condition is true, then it evaluates expression1. Otherwise, it will evaluate expression2.

Syntax

Following is the syntax of the ternary conditional operator −


Condition ? Expression1 : Expression2

Example

Swift program to explain ternary conditional operator.


import Foundation

let x = 20
let y = 2

// If x is greater than y then it will return 34 
// Otherwise return 56
var result = x > y ? 34 : 56

print(result)

Output


34

swift_operators.htm

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *