Swift Operators

Operators in Swift can be:
 Unary, which requires only one operand or input.(e.g. -a)
Binary, which requires two operands or inputs. (e.g. a+b)
Ternary, which requires three operands. (e.g. ?:).
 

Swift Assignment Operator

The assignment operator initializes or updates a variable.

var name = "John Doe"

name = "Dave Mathias"

 

Swift Comparison operators

The comparison operator returns a Boolean true if the statement is true or a Boolean false if the statement is not true.

Swift comparison operators
 

Swift Arithmetic operators

The arithmetic operators perform the four basic mathematical operations: add, subtract, multiply, divide.

Swift arithmetic operators
 

Swift Remainder operator

The remainder operator calculates the remainder if the first operand is divided by the second operand.

var num1 = 20, num2 = 3

num1 % num2 // remainder is 2

 

Swift Increment, decrement and Compound operators

The increment and decrement operators are shortcuts to increment or decrement a variable by 1.

The compound assignment operators combine an arithmetic operator with an assignment operator.

Swift increment, decrement and compound operators
 

Swift Logical operators

Logical AND operator returns true if both operands are true, otherwise it returns false.

The logical OR operator returns true if either of the operands is true.

The logical NOT operator inverts a Boolean value.

var bool1 = true, bool2 = false

bool1 && bool2  // false

bool1 || bool2  // true

!bool1  // false

 

Swift Ternary operator

Ternary operator can be used as a short form for if else conditions.

The ternary conditional operator assigns a value to a variable, based on the condition in first parameter.

Syntax:


boolean expression ? value if true : value if false

Example:

var x = 10

var msg = x > 0 ? "positive" : "negative or zero"

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags