Basic Operators in Swift

Operators are special symbols or phrases that you use to check, change, or combine values. Think of them as the verbs in the language of programming, performing actions on the "nouns" (which are the data). Swift provides a variety of operators to perform different kinds of operations, including mathematical calculations, comparison checks, logical operations, and more.

article

Operators are special symbols or phrases that you use to check, change, or combine values. Think of them as the verbs in the language of programming, performing actions on the "nouns" (which are the data). Swift provides a variety of operators to perform different kinds of operations, including mathematical calculations, comparison checks, logical operations, and more.


Basic Operators in Swift


Let's start with the basics. Basic operators in Swift include arithmetic, assignment, comparison, and logical operators.


Arithmetic Operators


Arithmetic operators are probably what you'd first imagine when thinking about math in programming. They include:


  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)
  • Remainder (%)

Here's how they work:


    
 let sum = 5 + 3  // Equals 8
let difference = 10 - 2  // Equals 8
let product = 4 * 2  // Equals 8
let quotient = 16 / 2  // Equals 8
let remainder = 10 % 4  // Equals 2
    

Assignment Operator


The assignment operator (=) initializes or updates the value of something. It's how you set or change the data.

    
var a = 10
a = 20  // Now, a is 20
    

Comparison Operators


Comparison operators compare values and determine if one value is greater than, less than, equal to, or not equal to another. They are crucial in making decisions in your code.


  • Equal to (==)
  • Not equal to (!=)
  • Greater than (>)
  • Less than (<)
  • Greater than or equal to (>=)
  • Less than or equal to (<=)

    
        let isEqual = (5 == 5)  // true, because 5 is equal to 5

    

Logical Operators


Logical operators combine or invert boolean logic values (true and false). They are the building blocks of more complex conditions in programming.

  • ogical AND (&&)
  • Logical OR (||)
  • Logical NOT (!)

    
        let and = true && false  // false
        let or = true || false  // true
        let not = !true  // false
    

Conclusion


Operators are the building blocks of programming in Swift, enabling you to perform a wide range of operations on data. By understanding and utilizing operators, you lay the foundation for more complex and powerful programming tasks.


instructor

Exodai INSTRUCTOR!

Johan t'Sas

Owner and Swift developer!