Swift 2.0 for programmers Part#1


Key points about Swift programming language:

  • Swift is not a superset of C or C++. Whereas, Objective-C was a superset of C.
  • Swift statements do not require semicolon. The compiler won’t complain if you use one, but it is recommended not to.
  • There is no main method/function in Swift. Code executes from top and works on its way down (like Python)
  • You can and should use playground, to quickly test your newly learned Swift code and then add the code chunk to your main project.

Variable

Use var to declare variable in Swift

var aVariable = 5
var aString = "Hello World"
var aBool = true 

Points to be noted:

  • Swift is a stronly typed language.
  • It inferres the type of the variable from initial value.
  • Once defined a type of a variable, you can not change it to another type.

if we do not want to provide initial value, we need to tell the type explicitely.

var anIntVariable : Int 		// anIntVariable is of type Int 
var aStringVariable : String 
var aFloatVariable : Float 		// 32-bit floating point 
var aDoubleVariable : Double 	// 64-bit floating point 
var aCharVariable : Character
var aBoolVariable : Bool 

if we want to mention the type as well a value

var aStringVariable : String = "Hello World" // although we don't need to tell the type as we are passing an initial value 

Constants

Use let to declare a constant

let aConstant = "Friday"

Constant varaible can be set only once. Although, You can declare it in one place and set the value later.
However, Playgournd does not support the feature yet. that means, you have to set constant value right away in playground.
that also means, you can declare a constant and set it value later in project.

Using constants is encouranged in Swift language and it is important. It is considered best practice to use constant wherever possible. The reasons are,

  1. It is a safety feature.
  2. There are some compiler level optimation and performance improvements if you use constant, instead of varaible.

Tips

You will be surprised, how much we are tempted to use var keyword but actually change the value of the variable in its lifetime. We could use let instead.

Print

print("Hello World")

var anIntVariable = 5
print(anIntVariable)

print("The value is \(anIntVariable) Great!")	// The value is 5 Great!

Conversion/Casting

var aDouble = 3.5
var anInt = 5

var result = aDouble * anInt 			// compile error.

Why??

Swift does NOT implicitly convert values.
anInt variable will not be casted to Float variable.

var result2 = Int (aDouble) * anInt 	// OR,
var result3 = aDouble * Double (anInt)

If statements

if a > 5 {
	
} 

if b == 0 {
	
} else {
	
}

if a > 5 && b == 0 {
	
}

if a > 5 || b == 0 {
	
}

Points to be noted

  • Parenthesis is not required around the condition, however, you can put them
  • Curly braces is MANDATORY is Swift, even if there is only one line to execute inside if
  • Conditions must be boolean true or false. Integer variable 0 will NOT be considered false.

Switch statements

let anInt = 10

switch anInt {
case 0:
	print("0")
case 1:
	break
default: 
	break
}

// switch statement with range 

switch anInt {
case 0...3:			// closed range operator (inclusive)
    break
case 4...5:
    break
default:
    break
}

Points to be noted

  • switch statements must be exhaustive. You have to define all possible cases inside switch. of course you can use default as a fallback of missing cases
  • Fall through does not supported by Swift. You have to have at least one statement inside each case. If there is none then use break

Loops

for var i = 0; i < 10; i++ {
    print(i)
}

for i in 1...10 {       // closed range operator (inclusive)
    print(i)
}

for i in 0..<10 {       // half-open range operator (last exclusive)
    
}

var a = 5

while a > 5 {

}

repeat {            // same as do-while in other languages
    
} while a > 5

Points to be noted

  • Curly braces is MANDATORY is Swift, even if there is only one line to execute inside loop

Functions

func aFunction () {
	print("Hello World")
}

// to call 
aFunction()

func aFunction(name: String, id: Int) {
	
}

// to call 
aFunction("Hello", id: 1)

func sum(firstNumber : Int, secondNumber : Int) -> Int {
    return firstNumber + secondNumber
}

// to call 
var res = sum(5, secondNumber: 3)

// default parameters 
func dataFunc(firstName : String = "John", lastName: String = "Doe", id: Int = 0) -> String {
    return "First Name: \(firstName), Last name: \(lastName) Id: \(id)"
}

// to call 
dataFunc()
dataFunc("James")
dataFunc("James", lastName: "Bond")
dataFunc(id: 5)

Points to be noted

  • Function input parameters are by default Constants!

UVa: 12250 (Language Detection)


// https://uva.onlinejudge.org/external/122/p12250.pdf

// @BEGIN_OF_SOURCE_CODE

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <bitset>
#include <utility>
#include <set>
#include <ctime>

#define Inf 2147483647
#define Pi acos(-1.0)
#define N 10000 + 10
#define LL long long
#define F(i, n) for( int i = (0); i < (n); i++ )
#define Fs(i, sz) for( size_t i = 0; i < sz.size (); i++ )
#define Set(a, s) memset(a, s, sizeof (a))
inline LL Power(int b, int p) { LL r = 1; for ( int i = 1; i <= p; i++ ) r *= b; return r; }

using namespace std;


int main ()
{
    string helloArray [] = {"HELLO",
            "HOLA",
            "HALLO",
            "BONJOUR",
            "CIAO",
            "ZDRAVSTVUJTE"};

    string languageArray [] = {"ENGLISH",
            "SPANISH",
            "GERMAN",
            "FRENCH",
            "ITALIAN",
            "RUSSIAN"};


    string input;
    int cases = 0;

    while (cin >> input && input != "#") {

        int len = 6;
        bool found = false;

        for ( int i = 0; i < len; i++ ) {
            if (helloArray [i] == input) {
                printf ("Case %d: %s\n", ++cases, languageArray [i].c_str());
                found = true;
                break;
            }
        }

        if (!found) {
            printf ("Case %d: UNKNOWN\n", ++cases);
        }

    }

    return 0;
}

// @END_OF_SOURCE_CODE

UVa: 1124 (Celebrity jeopardy)


// https://uva.onlinejudge.org/external/11/p1124.pdf

// @BEGIN_OF_SOURCE_CODE

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <bitset>
#include <utility>
#include <set>
#include <ctime>

#define Inf 2147483647
#define Pi acos(-1.0)
#define N 10000 + 10
#define LL long long
#define F(i, n) for( int i = (0); i < (n); i++ )
#define Fs(i, sz) for( size_t i = 0; i < sz.size (); i++ )
#define Set(a, s) memset(a, s, sizeof (a))
inline LL Power(int b, int p) { LL r = 1; for ( int i = 1; i <= p; i++ ) r *= b; return r; }

using namespace std;


int main ()
{
    string input;

    while (getline(cin, input)) {
        cout << input << endl;
    }

    return 0;
}

// @END_OF_SOURCE_CODE

UIU: Competitive Programming: File IO


1. Create a file named “in.txt” in same location of your source cpp file

2. Write two integer number in “in.txt” file

for example,
2 5


// @BEGIN_OF_SOURCE_CODE
 
#include <cstdio>
 
using namespace std;
 
int main(int argc, const char * argv[])
{
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
 
    int a, b;
 
    scanf ("%d %d", &a, &b);
 
    printf ("%d\n", a + b);
 
    return 0;
}
 
// @END_OF_SOURCE_CODE

UIU: Competitive Programming: GCD & LCM



// @BEGIN_OF_SOURCE_CODE
 
#include <cstdio>
 
using namespace std;
 
int gcd(int a, int b)
{
    if ( a == 0 ) return b;
 
    return gcd(b % a, a);
}
 
int lcm(int a, int b)
{
    return (a * b) / gcd(a, b);
}
 
int main(int argc, const char * argv[])
{
    printf ("%d\n", gcd(42, 36));
 
    printf ("%d\n", gcd(36, 42));
 
    printf ("%d\n", lcm(36, 42));
 
    return 0;
}
 
// @END_OF_SOURCE_CODE


// TODO: using prime factor 

UIU: Competitive Programming (Session 02): Task 03 Solutions


Task 03 Problems

  1. http://codeforces.com/problemset/problem/1/A
  2. http://codeforces.com/problemset/problem/4/A
  3. http://codeforces.com/problemset/problem/158/A
  4. http://codeforces.com/problemset/problem/71/A
  5. http://codeforces.com/problemset/problem/118/A
  6. http://codeforces.com/problemset/problem/158/B
  7. STL Vector: http://wp.me/poiaX-XB
  8. C++ String: http://wp.me/poiaX-Uc

There might have been some mistakes and/or logical errors in the real time videos. Correct solutions can be found below of this post.

Discussion Video

YouTube Video (Part 1)

Original file: MediaFire (Part 1)

http://www.mediafire.com/download/7nwx5gzc72a4dpy/ (250 MB)

Converted file (Smaller size): MediaFire (Part 1)

http://www.mediafire.com/download/kpa10g1ezdi265g/ (85 MB)

YouTube Video (Part 2)

TBD

Original file: MediaFire (Part 2)

TBD

Converted file (Smaller size): MediaFire (Part 2)

TBD

Sourcecode

CodeForces 1A (Theatre Square)

http://wp.me/poiaX-15U

CodeForces 4A (Watermelon)

http://wp.me/poiaX-15Z

CodeForces 158A (Next Round)

http://wp.me/poiaX-164

CodeForces 71A (Way Too Long Words)

http://wp.me/poiaX-168

CodeForces 118A (String Task)

http://wp.me/poiaX-16c

CodeForces 158B (Taxi)

http://wp.me/poiaX-16f