Category Archives: TUTORIALS

Detailed tutorials explaining how to build most common applications, in different languages.

Longest Substring Without Repeating Characters

Task

Task:
Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", which the length is 3.

 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

 

Example 3:

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

 

This problem was taken from Leetcode

Solution

The sliding window solution.

The sliding window represents a range of elements like an array,  defined by the start and end indices. Then we start moving “sliding” the indices to the next checked subset.

Let’s say that we have this string: “ABCDECFGH”.
The answer of the problem is “DECFGH“.

The obvious resolution could be to grab each letter of the string (starting with the first one), compare it with a buffer of the letters that we already checked and if there is match, continue with the next letter and keep track of the length of the longest string sequence without repeated characters.

In the current example “ABCDECFGHlet’s name is S we start with starting index i  = 1, and end index j = 1. so S[i, j)

Then we start “sliding” j adding more elements in the range and comparing next element added in the range with all previous elements till we find match. I our example this will happen on i = 1 and j = 6 since 6th letter is C and C is already in the range at position 3. Let’s call it j1 = 3.

Then the next step will be to “slide” i and start all over. i = i + 1.

But we could improve this algorithm in two ways:

  1. Store the characters in the buffer into an associative array or so called hashmap where the key will be the character, and the value the index. Example:
    { key = A, val = 1 }
    { key = B, val = 2 }

    This way we don’t have to iterate through each element into the buffer when checking if the character is there or not.
  2. When we find match, we don’t have to start from the next character but we can “slide” to the value of the character in the buffer that matched + 1 since we already know, that the sequence before has shorter length.
    In the range [i, j1] which in the current example is [1, 3] we know for sure that there will be no substring longer than the current one [i, j] so we don’t have to “slide” i = i + 1 but we could do i = j1 + 1 which will save checking of [i+1, j1]  (B and C)
    Example:
    start checking ABCDE and then C is already found in the buffer at index = 3. So instead of starting from index 2 – B we could start from index 3 + 1 which is D

Longest Substring Without Repeating Characters solution diagram

The solutions:

Java Script

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {


    var hashMap = {};    

    function findUniqueSequence(left) {
        var buffer = [];
        
        for(var c = left;c < s.length; c ++) {            
            if(buffer.includes(s[c])) {
                var symbol = s[c];
                var nextPos = hashMap[symbol] + 1;
                return [buffer, nextPos ];
            }
            hashMap[s[c]] = c;
            buffer.push(s[c]);
        }
        return [buffer, s.length];
    }


    var left = 0; 
    var longest = [];       
    while(left < s.length) {
        var result = findUniqueSequence(left);
        left = result[1];
        longest = longest.length < result[0].length ? result[0] : longest;
        if(s.length - left < longest)
            break;
    }
    return longest.length;    
};

 

C++

class Solution {
    
public:
    int lengthOfLongestSubstring(string s) {
        unsigned long n = s.length();
        char char_array[n+1];
        strcpy(char_array, s.c_str());
        
        int left = 0;
        unsigned long arr_length = sizeof(char_array) - 1;
        int longestStringSize = 0;
        int sizeCounter = 0;
        
        std::map<char, int> buffer;
        int co = 0;
        while (left < arr_length) {
            char cursor = char_array[left];
            
            if(buffer[cursor] == 0) {
                buffer[cursor] = left + 1;
                sizeCounter ++;
                left ++;
            }
            else {
                left = buffer[cursor];
                buffer.clear();
                longestStringSize = sizeCounter > longestStringSize ? sizeCounter : longestStringSize;
                sizeCounter = 0;
            }
        }
        longestStringSize = (longestStringSize == 0 || sizeCounter > longestStringSize) ? sizeCounter : longestStringSize;
        return longestStringSize;
    }
};

 

Adding Config file and Babel loader

branch-name:  
Click To Copy

Why adding Babel ?

Java Script is a language that evolves really fast, but unfortunately many people still use old browsers that doesn’t support the latest Java Script syntax.

Let’s say that we would like to be at the edge of the technology and use the latest ECMA Script 6 or (European Computer Manufacturers Association) or EC for shorter and we want to use the latest one EC6. The solution will be to `transpile` the new EC6 to older version, that is supported even with the old browsers.

But Webpack is just JS bundle creator and it doesn’t know how to translate the new EC6 syntax to the old one and here comes the Webpack loaders.

Webpack loaders simply pre-process the files which Webpack is going to bundle.

There are tons of loaders, you could check them here https://webpack.js.org/loaders/ but the one that we need for this particular task is called Babel

There are two ways of adding loaders: with a config file or from the package.json. Since doing it through a config file is more flexible we will explore this option.

Adding Babel loader and Webpack config file.

In order to use Babel loader, we have to tell Webpack about it.

Adding Webpack config file.

 Just creating webpack.config.js in the root folder of our project is enough to create Webpack config file, which Webpack will pick up automatically from this location.

But for our particular task we need to add Babel loader to our project. So first before we move any further, let’s do this:

Babel got split in a couple of sub-modules that we need to add:

  • babel-core
  • babel-loader
  • babel-preset-env – for compiling Javascript ES6 code down to ES5

yarn add @babel/core babel-loader @babel/preset-env

– create new file called webpack.config.js in the root of the project folder with these contents:

./webpack.config.js

module.exports = {
  mode: 'development',
  entry: [
    './src/app.js'
  ],
  output: {
    filename: '[name]-bundle.js',
  },  
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  }
};

What we just did:
– we created a brand new file called webpack.config.js in the root folder of our project and Webpack will look there and pick it up.
– we added mode: “development” insted of passing it through the build script (line 2)
– added entry point to to tell webpack where to look for the bundle files.
we could have skip this parameter if we name our bundle entry point was named ./src/index.js and Webpack was going to pick it automatically, but for the purpose of understanding Webpack config we customized it with ./src/app.js
– added output parameter to specify Where webpack should create the bundle.
By default if this parameter is not specified Webpack will create ./dist/main.js bundle.
– we added a Babel module config, that is going to transpile all JS files matching this RegExp pattern /\.js$/ and make them old fashioned JS that all browsers understand.
– we told Webpack to exclude node_modules “exclude: /node_modules/,” (line 13) since this folder is where npm installs packages and it doesn’t need to be transpiled.

Now we have to tell Babel how to transpile our files to JavaScript. Create .babelrc in the root of the project, with these contents:

./.babelrc

{
  "presets": [
    "@babel/preset-env"
  ]
}

Presets are like plug-ins. They describe which ES features we are going to use so Babel could transpile back to ES5 that all browsers will understand. In our case we added @babel/preset-env so we could use latest ES coding, and since we are going to add React we added @babel/preset-react which under the hood includes:

so Babel will know how to deal with react-jsx files.

Let’s give it a try:

yarn build-dev

and check the ./dist folder. Looks good right ?

But if you try to run in on old IE you will notice that the site break. We still need babel-polyfill to  emulate a full ES2015+ environment (no < Stage 4 proposals). This woks on the front end only.

Adding Babel-polyfill.

Let’s install the library first: yarn add @babel/polyfill

There are two different ways to add it: we could use require(“@babel/polyfill”); or import “@babel/polyfill”; or we could use Webpack to add it.

Let’s use Webpack:

./webpack.config.js

module.exports = {
  mode: 'development',
  entry: [
    '@babel/polyfill',
    './src/app.js'
  ],
  output: {
    filename: '[name]-bundle.js',
  },  
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  }
};

Now we added support for all old browsers.

Adding another pre-processor: Eslint.

Now we know how to add Webpack modules, let’s add another one, that will help us identify problems with our code even before we compile it.

yarn add eslint eslint-loader babel-eslint eslint-plugin-react --dev

what we just did:
– we installed:
eslint – the core JS linter
eslint-loader – tells webpack that we are going to use eslint in our build
babel-eslint – provides linting for ES6 code.
eslint-plugin-react – Since we are going to use React, we have to install the React plugin for
eslint.

The easiest way to configure eslint is through .eslintrc config file. Let’s create one in the root folder with these contents:

./.eslintrc

{
  "parser": "babel-eslint",
  "plugins": [
    "react"
  ],
  "rules": {
    "no-undef": 1
  }
}

what we just did:
– we set up the parser to be babel-eslint (line 1)
– we added react plugin
– we added one rule “no-undef” with a value ‘1’. The possible values are: 0 = off, 1 = warn, 2 = error

Now in the root folder execute:
./node_modules/eslint/bin/eslint.js .

the output probably will be similar to this:

~/babel-webpack-react-boilerplate/dist/main-bundle.js
45:48 warning ‘Symbol’ is not defined no-undef
46:44 warning ‘Symbol’ is not defined no-undef

~/babel-webpack-react-boilerplate/src/test.js
3:3 warning ‘console’ is not defined no-undef

✖ 3 problems (0 errors, 3 warnings)

….

Let’s add a script to execute linter through npm.

"scripts": {
  "clean": "rm -rf ./dist",
  "lint": "eslint .",
  "build-dev": "webpack --mode development ./src/app.js -o ./dist/main-bundle.js",
  "build-prod": "webpack --mode production ./src/app.js -o ./dist/main-bundle.js"
},

And give it a try:
yarn lint

 NPM always looks first in project’s node_modules folder, so if you have eslint (or any other module) installed globally and locally, it will always pick the local version.

Adding .eslintignore
And we could add the files that we don’t want to be checked into
./.eslintignore

dist
webpack.config.js

Let’s run the linter yarn lint

/Users/toninichev/Downloads/webpack-test/src/test.js
2:3 warning ‘console’ is not defined no-undef

✖ 1 problem (0 errors, 1 warning)

✨ Done in 1.38s.

Let’s say that we don’t want to `fix` this since this is not a real problem, but we want to tell Eslint to ignore it we could add /* eslint-disable no-undef */

./src/test.js

/* eslint-disable no-undef */

const test = (msg) => {
  console.log(msg);
}
export default test;

Run Eslint again and you sould not see any issues.

branch-name:  
Click To Copy

 

Webpack – Zero Config

branch-name:  
Click To Copy

Development vs Production modes.

When you ran the code from the previous tutorial you might notice this message:
WARNING in configuration
The ‘mode’ option has not been set. Set ‘mode’ option to ‘development’ or ‘production’ to enable defaults for this environment.

Webpack 4 is coming with two predefined modes: “development” and “production” and automatically optimize the code for the corresponding build.
To enable the corresponding mode we simply need to call Webpack with –mode development or –mode production parameter.
Let’s go to package.json and add ‘build’ script in so we could call it with npm without passing all parameters:

./package.json

  "scripts": {
    "build": "rm -rf ./dist && webpack --mode development ./src/app.js -o ./dist/main-bundle.js"
  }

Let’s execute the script that we just added and create a new bundle.

yarn build

But why stopping there? We could configure Webpack with no parameters at all. Just passing –mode.

Setting Webpack with Zero config

Webpack by default will look for entry point in ./src/index.js and will output the bundle in ./dist/main.js

Change the script section in package.json as follows.

"scripts": {
  "clean": "rm -rf ./dist",
  "build": "webpack --mode development"
},

what we just did:
– we added a clean up script (line 2) that will take care of deleting the old bundle once executed.
– we added ‘build’ script, with almost 0 config parameters.

Now if we rename src/app.js to src/index.js Webpack will pick it ot automatically and will output the bundle code in dist/main.js

We also removed ‘rm -rf’ and added it into another script called clean.
Now in the console in the root of the project if we do:

yarn run clean
yarn run v1.3.2
$ rm -rf ./dist
✨ Done in 0.11s.
$ yarn run build
yarn run v1.3.2
$ rm -rf ./dist && webpack –mode development ./src/app.js -o ./dist/main-bundle.js
Hash: 3e7c9702fe472d8df3d2
Version: webpack 4.16.3
Time: 98ms
Built at: 08/01/2018 4:10:30 PM
Asset Size Chunks Chunk Names
main-bundle.js 4.48 KiB main [emitted] main
Entrypoint main = main-bundle.js
[./src/app.js] 55 bytes {main} [built]
[./src/test.js] 69 bytes {main} [built]
✨ Done in 1.06s.

We well see that Webpack prepared a bundle for us with Zero Config parameters.

Setting Webpack override

The Zero Config was great but if the complexity of the project grows, we will need to customize Webpack so let’s revert the changes back.
– Rename src/index.js back to src/app.js
– Change the scripts parameters in package.json to look like this:

"scripts": {
  "clean": "rm -rf ./dist",
  "build-dev": "webpack --mode development ./src/app.js -o ./dist/main-bundle.js",
  "build-prod": "webpack --mode production ./src/app.js -o ./dist/main-bundle.js"
},

What we just did:
– We added back “clean” script to remove ./dist folder.
– We added “build-dev” and “build-prod” build scripts.

Let’s give it a try. From the terminal run:

yarn clean

This will get rid of the ./dist folder.

yarn build-dev

and look at ./dist/main-bundle.js Nothing unusual there. The main-bundle.js was re-created.

Let’s check the production build script. Run:

yarn build-prod

now it gets interesting, if you look at ./dist/main-bundle.js you will notice that it is minified and prepared for production use. Webpack also uses UglifyJSPlugin when “–mode” is set up to “production”.

Now you have production build ready!

 What is far from true is that this is really production ready but we will figure out this later in this tutorial.

branch-name:  
Click To Copy

 

Webpack – Getting Started

How to use this tutorial ?

The table of contents of this tutorial is located on the right side

There are two projects that we need:
– the front-end website that we are going to build in this tutorial,
GraphQL server which we are going to use later in “Adding Apollo provider and introduction to making queries to GraphQL“.

There are two GitHub repositories with the complete projects located here:
GitHub:WebpackReactReduxApolloTutorial

And the GraphQL server located here
GitHub:graphql-boilerplate

Instructions of how to set up GraphQL server could be found HERE.

When you go through each chapter you could check out the appropriate branch which contains the chapter specific code, instead of looking at the complete project.
This way will be easier to follow the developing process. Each branch name could be found at the beginning and the end of the tutorial. Look for branch-name: XXXXX

In general it would be better if you follow the tutorial and build the website yourself but if you get stuck somewhere feel free to clone the repository and check out the appropriate branch.

Setting up the project

branch-name:  
Click To Copy

 

mkdir babel-webpack-boilerplate
cd babel-webpack-boilerplate
yarn init -y
yarn add webpack webpack-cli --dev

What we just did:
– line 1: created project’s folder
– line 2: navigate to project’s folder root
– line 3: executing yarn init -y initialized our new project. – y simply means ‘answer yes and use the default init settings’. A package.json is created, which is used to describe the npm project dependencies and executable scripts.
– line 4: we added Webpack as a dev dependency (–save-dev) in our project.

Creating project’s files

Using your favorite text editor create index.html in the root folder of the project, with plain html, and a script tag to include our bundled Java Script code (Line 9).

./index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Babel Webpack Boilerplate</title>
    </head>
    <body>
        <h1>Babel Webpack React Boilerplate</h1>
        <script type="text/javascript" src="dist/main-bundle.js"></script>
    </body>
</html>

Create folder to store the actual bundle files:

mkdir ./src

Create the actual bundle files:

src/app.js

import test from './test';
test('Babel is running!');

src/test.js

const test = (msg) => {
  console.log(msg);
}
export default test;

and dist folder to store compiled bundle:

mkdir ./dist

The project’s layout should look like this:

babel-webpack-react-boilerplate
├── dist
├── index.html
├── node_modules
├── package.json
├── src
|        ├── app.js
|       └── test.js
└─ package.lock

* package.lock is used to describe which versions of node modules are installed, and is create automatically after executing npm install, so don’t worry if it’s not there yet.

Running Webpack and creating Java Script bundle.

Now we have laid out a simple project, let’s create a bundle and run it.
In the terminal in the project’s root folder execute

./node_modules/webpack/bin/webpack.js ./src/app.js -o ./dist/main-bundle.js

What we just did:
– we called Webpack from the command line.
– passed the entry point ./src/app.js to create the bundle.
– and the output file -o ./dist/main-bundle.js

Now if we look at the ./dist folder, we will see that the bundle.js is created.

Testing the project

Open your browser and navigate to the the project’s root.

Look at the console and you will see ‘Babel is running!’.

Congratulations, you just created your first bundle!

branch-name:  
Click To Copy

 

 

where to go from here ?

Add Two Numbers

Task

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Examples :

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

This problem was taken from Leetcode

Solution

The solution:

Java Script

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */



function ListNode(val, next) {
  this.val = (val===undefined ? 0 : val)
  this.next = (next===undefined ? null : next)
}


/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
  
  function doSum(a,b, carry) {
    var result = {
      val: 0,
      carry: 0
    }
    var sum = a + b + carry;
    if(sum > 9) {
      result.val = sum - 10;
      result.carry = 1;
    }
    else {
      result.val = sum;
      result.carry = 0;
    }
    return result;
  }

  var nodeA = l1;
  var nodeB = l2;
  var end = false;
  var carry = 0;
  var result = new ListNode(0, null);
  var resultPointer = result;
  var tmp = null;

  while(nodeA != null || nodeB != null) {
    var valA = nodeA == null ? 0 : nodeA.val;
    var valB = nodeB == null ? 0 : nodeB.val;
    var sumResult = doSum(valA, valB, carry);
    carry = sumResult.carry;
    
    resultPointer.val = sumResult.val;
    resultPointer.next = new ListNode(0, null);
    tmp = resultPointer;
    resultPointer = resultPointer.next;

    nodeA = nodeA ? nodeA.next : null;
    nodeB = nodeB ? nodeB.next : null;
  }

  if(carry != 0) {
    tmp.next.val = carry; // add carry to the val of the last node
  }
  else 
    tmp.next = null; // remove the last empty node.
  return result;
};




var l1 = new ListNode(9, 
          new ListNode(9,
          new ListNode(9,
          new ListNode(9, null)
      ))
);

var l2 = new ListNode(9, 
          new ListNode(9,
          new ListNode(9,
          new ListNode(9,
          new ListNode(9,
          new ListNode(9,                    
          new ListNode(9, null)
      )))))
)

// [9,9,9] , [9,9,9,9,9]
// result: [8,9,9,0,0,1]

var result = addTwoNumbers(l1, l2);

console.log(result);

Climbing stairs

Task

You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.


Example 1:

Input: 2
Output: 2

Explanation:

 There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps


Example 2:

Input: 3
Output: 3

Explanation:

 There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

 

This problem was taken from Leetcode

Solution

The solution:

Let’s look at the possible scenarios:

[table id=1 /]

If we look at the # of ways to climb, we clearly see that the ways to climb grows in Fibonacci sequence: 1, 2,  3,  5,  8,  13, 21

Then all we need to do is to iterate n times (where n  is the number of stairs) and to find the corresponding Fibonacci number.

Using while loop

  • basically we use temp to store previous Fibonacci number temp = a , initially 1
  • then we calculate the next number a = a + b , initially a = 0 + 1
  • then we set up b = temp which stores the last Fibonacci number in order to be ready for the next iteration. Initially 1.

Looking at the numbers from the first iteration, it is clear that on the second one we will have:
temp = a = 1
a = a + b = 1 + 1 = 2
b = temp = 1

third iteration will produce:
temp = a = 2
a = a + b = 2 + 1 = 3
b = temp = 2
forth iteration:
temp = a = 3
a = a + b = 3 + 2 = 5
b = temp = 3

and so on … a will always return the Fibonacci number for the current n position.

Java Script

/**
 * @param {number} n
 * @return {number}
 */
var climbStairs = function(n) {
    if( n < 4) 
        return n;

    fibonacci = function(n) {

        var a = 1, b = 0, temp, num = 1;

        while(num <= n) {
            temp = a;
            a = a + b;
            b = temp;
            num ++;
        }
        return a;
    }

    return fibonacci(n);
};

Using For loop

This is the easiest to comprehend:

  • we create an array to store the Fibonacci numbers var fn = [1,1] with the first two numbers pre-set so the for loop could generate the next one.
  • created for loop that picks the fn[i - 1] and fn[i - 2] numbers and generate the next one.
  • pushed newly calculated Fibonacci number into an array so we could use to generate next one.
  • keep looping till we reached i < n + 1 which is the  answer.

Java Script

/**
 * @param {number} n
 * @return {number}
 */
var climbStairs = function(n) {
    if( n  < 3)
    return n;
    
    var fn = [1,1];
    for(var i = 2; i < n + 1; i ++) {
        var nextNumber = fn[i - 1] + fn[i - 2]; 
        fn.push(nextNumber);
    }

    return fn[fn.length - 1];
};

 

Third solution: Using recursive function.

Java Script

/**
 * @param {number} n
 * @return {number}
 */
var climbStairs = function(n) {
    if( n < 4) 
        return n;

    fibonacci = function(n) {
        if(n < 2) {
            return n;
        }
        var result = fibonacci(n - 1) + fibonacci(n - 2);        
        return result;
    }

    return fibonacci(n + 1);
};

The idea here is to call fibonacci(n) function to generate the next Fibonacci number.
For n < 2 the function will simply return n 0,1,2.
For n = 3 the function will call itself recursively asking for previous two Fibonacci numbers (2 and 1) and will calculate the next number which is the sum of the previous two, and so on.

Optimize the recursive function to use Memoization.

Memoization is simple technique where we are storing the value of already computed parameter into a HashMap function and quickly retrieve it when we need it.

In our current example since the keys are just a numbers we could store the Fibonacci numbers in a regular array (line 9). Then we simply check if the value already is set up into memo array and return it or call fibonacci function once again.
Then we set up memo array with the next solved Fibonacci number with index n

Java Script

/**
 * @param {number} n
 * @return {number}
 */
var climbStairs = function(n) {
    if( n < 4) 
        return n;

    var memo = [];
    fibonacci = function(n) {
        if(n < 2) {
            return n;
        }
        var a = memo[n - 1] ? memo[n - 1] : fibonacci(n - 1);
        var b = memo[n - 2] ? memo[n - 2] : fibonacci(n - 2);

        return memo[n] = a + b;
    }

    return fibonacci(n + 1);
};

 

You might also want to check Fibonacci sequence generator.

Brief Introduction to SWIFT types

Playground located at:  https://github.com/ToniNichev/Swift-Data-Types

  • Arrays

Arrays store data of the same type in the same order (sorted)
– line 1 demonstrates creating an array syntax.
– line 7 shows the shorthand array creation syntax
– line 13 shows creating an array with Array literal (and default values)

[csharp highlight=”2,7,13″]
// create empty array
var myArrayOne = Array<String>()
myArrayOne.append(“Test Value”)
print(“Array one value: \(myArrayOne[0])”)

// or using shorter syntax
var myArrayTwo = [Int]()
myArrayTwo.append(1)
myArrayTwo.append(2)
print(“Array one value: \(myArrayTwo[1])”)

// or with default values using array literal
var myArrayThree = [“one”, “two”, “three”]
print(“Array one value: \(myArrayThree[1])”)

// or
var myArrayFour = Array(repeating: 5, count: 3)
print(“Array count: \(myArrayThree.count)”)

//iterating over an array
for item in myArrayTwo {
print(item)
}
[/csharp]

result:

Array one value: Test Value
Array one value: 2
Array one value: two
Array count: 3
1
2

Although arrays can only store elements of the same type, it is still possible to store elements from different types by creating array of Any type.
In the example below, an array of Any type is created, and populated with string, integer, double values and even another array. Then while iterating through the array elements we convert all values to string representation (line 9), and print them.

var mixedArray = Array&lt;Any&gt;()
mixedArray.append("This is string") // adding string
mixedArray.append(123) // adding integer
mixedArray.append(2.64) // double value
mixedArray.append(myArrayTwo) // adding another array

print("Printing values of mixed array, converted to strings")
for item in mixedArray {
let val: String = String(describing: item)
print("\(val)")
}

 

 

[csharp highlight=”9″]
var mixedArray = Array<Any>()
mixedArray.append(“This is string”) // adding string
mixedArray.append(123) // adding integer
mixedArray.append(2.64) // double value
mixedArray.append(myArrayTwo) // adding another array

print(“Printing values of mixed array, converted to strings”)
for item in mixedArray {
let val: String = String(describing: item)
print(“\(val)”)
}
[/csharp]

result:

Printing values of mixed array, converted to strings
This is string
123
2.64
[1, 2]
  • Sets

Sets unlike arrays could only store unique values in unsorted order

[csharp highlight=”2,7,13″]

// create empty set
var mySetOne = Set<String>()
mySetOne.insert(“one”)
mySetOne.insert(“two”)
mySetOne.insert(“three”)
print(“mySetOne does contain’two’ : \(mySetOne.contains(“two”)) “)

// iterating
for item in mySetOne {
print(“mySetOne: \(item)”)
}

// we could create sets using Array literal too
var mySetTwo: Set&amp;amp;amp;amp;amp;lt;String&amp;amp;amp;amp;amp;gt; = [“One”, “two”]
[/csharp]

result:

mySetOne does contain'two' : true 
mySetOne: one
mySetOne: three
mySetOne: two
  • Dictionaries

    Dictionaries are pretty much like arrays, but they store values against keys

[csharp]
// dictionary with integer values
var myDict = [String: Int]()
myDict[“one”] = 1
myDict[“two”] = 2
print(“myDict value at positon ‘one’: \(myDict[“one”]!)\n”)

// dictionary with different types of objects
var obj = [String: AnyObject]()
obj[“one”] = “12345” as AnyObject?

// velue two, contains second dictionary
obj[“two”] = [“user”: [“name”: “Jim”, “email”: “jim@yahoo.com”] ] as AnyObject?
obj[“three”] = “1221” as AnyObject?

// value ‘four’ is Integer
obj[“four”] = 25 as AnyObject

//getting second dictionary inside value ‘two’
var subDict = obj[“two”]! as! [String: AnyObject]
print(“\n’subDict’ value: \(subDict)”)

// retreiving specific value
var subDict_user_name = ((obj[“two”]! as! [String: AnyObject])[“user”] as! [String: AnyObject])[“email”] as! String
print(“\n’subDict_user_name’ value: \(subDict_user_name)”)

[/csharp]

result:

myDict value at positon 'one': 1


'subDict' value: ["user": {
 email = "jim@yahoo.com";
 name = Jim;
}]

'subDict_user_name' value: jim@yahoo.com
  • Enumerations

Swift enumerations are common set of related cases

[csharp]
enum Locations {
case Bulgaria, USA, Australia

var address: String {
switch self {
case .Bulgaria:
return “Ohrid 3 b”
case .USA:
return “5711 Jefferson st”
case .Australia:
return “New zeland drive”
default:
return “No selection!”
}
}

var city: String {
switch self {
case .Bulgaria:
return “Velico Tarnovo”
case .USA:
return “West New Tork”
case .Australia:
return “Sidney”
default:
return “No selection!”
}
}
}

let country = Locations.USA
print(“COUNTRY: \(country) \nAddress: \(country.address) \nCity:\(country.city)”)
[/csharp]

result:

COUNTRY: USA 
Address: 5711 Jefferson st 
City:West New Tork

 

  • Closures

[csharp]

let s = double(2, 2)

testFunc(ParamA: 2, closureA: { (paramB) in
print(“>>>\(paramB)”)
}) {
print(“Closure 2”)
}
}
// a closure that has no parameters and return a String
var hello: () -> (String) = {
return “Hello!”
}

// a closure that take two parameters and return an Int
var double: (Int, Int) -> (Int) = { x, y in
return y * x
}
func testFunc(ParamA:Int, closureA:(_ paramB:Int)->(), closureB:()->()) {
let result = 2 * ParamA
closureA(result)
closureB()
}

[/csharp]

 

 

Playground located at:  https://github.com/ToniNichev/Swift-Data-Types