SWIFT FUNDAMENTALS WITH PROBLEM SOLVING

100 Days of Swift: Fundamentals — Basic Operators

Today I covered the topics based on the chapter — Basic Operators from the Swift Documentation.

Rudrank Riyam
100 Days of Swift and SwiftUI

--

Basic Operators

I have been using the basic operators since high school in C++. So, I won’t discuss what is already in the documentation, rather focus on the implementation of few of the operators.

Terminology

Operators can be classified into three type, unary, binary, or ternary —

  • Unary — Single target
!stack.isEmpty { // perform some action }
  • Binary — Two targets
carryOver = sum % 10
  • Ternary — Three targets
(number > 0) ? number : 0

Assignment Operator

We are aware that the assignment operator is used to assign (initialize or update) values. Sometimes, if you want to assign multiple values to multiple constants/variables, you can use a tuple.

let (firstName, lastName) = ("Rudrank", "Riyam")

Artihmetic Operators

There are four standard operators — Addition (+), Subtraction (-), Multiplication (*) and Division (/) that we are used to using since childhood.

Let’s focus on the Remainder Operator.

From the documentation, -

The remainder operator (a % b) works out how many multiples of b will fit inside a and returns the value that is left over (known as the remainder).

Question — We need to find all the numbers in a given array whose number of digits are even.

When we find a problem related to finding odd/even, we usually use the remainder operator.

Why? Because a number divided by 2 leaves a remainder 1/-1 if it is odd, otherwise 0 for even.

Hence we can just count the number of digits in a number and use the remainder operator to find if the number of digits are even or not.

Here’s a simplified solution where I converted the number into a string and counted the number of characters. :)

Question Source: LeetCode — 1295. Find Numbers with Even Number of Digits

Compound Assignment Operators

Coming from a C++/Java background, I have been used to i++ and ++i in for loop and other stuff. But this doesn’t work!

Digging deep on StackOverFlow, I got to know that the ++ and -- were deprecated in Swift 2.2 and removed in Swift 3. Sigh.

If you are interested in reading more about this, you can go through the official proposal SE-0004 to remove the ++ and -- operators authored by Chris Lattner.

matrix[rowStart++][column] = ++index;

in C++/Java is this syntax in Swift —

matrix[rowStart][column] = index + 1rowStart += 1

Not much difference, though.

Comparison Operators

There are six standard comparison operators:

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

Here’s a problem to use the equal to and less than operators.

Question — We are given an array of integers and a particular integer, we need to remove all the occurrence of this particular integer and the return the new length of the array, after removing.

We use the standard Two Pointers approach, where we have a left pointer at the index = 0, and the right pointer at the extreme end of the array.

When encountering the particular integer, we swap that integer with the last element, and decrement the right pointer to get the new length of the array. Note that we only need the length, not the new array.

Question Source: LeetCode — 27. Remove Element

Identity Operator

Identity operators === and !== can be used to check whether constants/variables refer to the same instance of a class or not.

To understand more about this with an example, refer to the article on “Comparing Instances using Identity Operators”

Ternary Conditional Operator

I have always used a ternary operator to convert a verbose if-else ladder into one line. It is actually a shorthand code for it.

Example, we can convert this code

if number > 0 {
return number
} else {
return 0
}

into this one line of concise code —

(number > 0) ? number : 0

However, when you are assigning values or trying to convert a nested if-else ladder into one single statement, make sure that the parentheses are properly placed and enclosed.

Nil-Coalescing Operator

A subtle example of using the nil-coalescing operator is retrieving the value from a dictionary for particular key, and if it does not exist, assign a default value of 0

let occurrence = mappingCharacterToCount["a"] ?? 0

(There is a better way for assigning a default value in a dictionary which will be discussed during Collection Types Day)

Range Operator

If you want each number in an array, the basic syntax is —

for number in numberArray { 
// perform something
}

Now, what if you want the index of each number?

We use the range operator.

Closed range operator includes both the values. For example,

for index in 0...(numberArray.count - 1) {
// -1 so index does not go out of bounds, duh
}

Half-open ranges are useful when working with data structures with zero-based index. You can use a half-open range in the above example as well.

var matrix = [[Int]](repeating: [Int](repeating: 0, count: 3), count: 3)for rowIndex in 0..<matrix.count {
for columnIndex in 0..<matrix[0].count {
// perform a cool matrix operation here
debugPrint(rowIndex, columnIndex, separator: "\t")
}
}

We can also use the indices instance property to get the range.

for rowIndex in matrix.indices {
for columnIndex in matrix[0].indices {
// perform a cool matrix operation here
debugPrint(rowIndex, columnIndex, separator: "\t")
}
}

There’s a relative(to:) instance method to return a concrete range of indices from a partial range.

From the documentation,

You can use the relative(to:) method to convert a range expression, which could be missing one or both of its endpoints, into a concrete range that is bounded on both sides. The following example uses this method to convert a partial range up to 4 into a half-open range, using an array instance to add the range’s lower bound.

We have another operator ~=(_:_:) to check a value is present in the range or not.

For example,

let lowercaseLetter = UnicodeScalar("a")if 97...122 ~= lowercaseLetter.value {
print("The ASCII value of \(lowercaseLetter) is \(lowercaseLetter.value)")
}

If you are interested in knowing more about different functions on Range, definitely checkout the documentation —

Logical Operator

Logical operators modify or combine the Boolean logic values true and false. Swift supports the three standard logical operators —

  • Logical NOT (!a)
  • Logical AND (a && b)
  • Logical OR (a || b)

Using the NOT Operator

Question — We are given a non-empty array of integers, every element appears twice except for one. We need to find that single element.

We start with a set data structure, and loop over the array.

If the set does NOT contain that number, we add it to the set. Otherwise, we remove that number. This way, all the numbers that appear twice will be inserted and then removed.

In the end, we will be left with only one number.

Question Source: LeetCode — 136. Single Number

Using the AND Operator

Question — We are given two strings A and B of lowercase letters. We return true if and only if we can swap two letters in A so that the result equals B.

The first step is to check whether the number of characters in A and B are equal or not. If they are not equal, that means they can never be the same, and we return false.

Second, if they are exactly equal, we need to check if we have unique characters in A or not. If there are unique characters such that A = abc, B = abc , then swapping any character of A will not result in B. Here, we use the Set data structure for getting the number of unique characters.

If A has at least one duplicate character, for example A = aab, B = baa , then we can swap to get the resultant B.

Now, for the main function, we append the index in an array indices where the character of A is not equal to the character at B while iterating through the characters of A.

If the count of indices is greater than two, that means there are more than two letters that need swapping to make A equal to B which contracts the condition given to us, and need to return false.

Now, the main part of the use of the logical operator.

We check if the character at indexOne of A is equal to the character at indexTwo of B AND character at indexOne of B is equal to the character at indexTwo of A.

We also use explicit parentheses here to make this expression easier to read.

If yes, that means we can swap them so that the A will be equal to B. Otherwise return false.

Question Source: LeetCode — 859. Buddy Strings

--

--

Rudrank Riyam
100 Days of Swift and SwiftUI

Apple Platforms Developer. Technical Writer & Author. Conference Speaker. WWDC '19 Scholar.