Saturday, April 23, 2016

Swift's enumerate

Swift has this sweet function called "enumerate". This is similar to "for x in array" loop but in addition to providing the element in the array, it also provides index of that element in that array.

The normal for loop is available in C++ as well

for(uint32_t i = 0 ; i < array.size(); i++)
{

}

or the range based for loop where we can get the elements without using index.

for(auto element : Array)
{

}

or the iterator based for loop from which you can calculate the index

for( auto itr = Array.begin(); itr != Array.end(); ++itr)
{
  auto index = itr - Array.begin();

}

But there is no current possible way to get both index and the element at the same time without  a little bit of extra effort by the programmer.

But in Swift 2.0, enumerate() can be used to get the index and element like so.

for(index, elem) in Array.enumerate(){
...

}

Now how cool is that? This would come in handy if you have to iterate through the array, and a second array with same size and aligned elements in correlation with the enumerated array has to be accessed at the same index.

Or if you need the index to erase/delete and element based on some conditions.

for(index, elem) in Array.enumerate(){
  if(condition){
    Array.removeAtIndex(index)
  }

}


That is all for today's post. Hope it was useful to you in one way or the other in understanding a little bit deeper into the programming tactics. 


Saturday, April 16, 2016

Convenient Swift

I am not talking about how convenient Swift is, in this blog, though it is obviously convenient. No. This is about  the keyword "convenience". In Swift init() is the inbuilt function keyword to initialize a class's instance. More or less like a C++ constructor. I say more or less  because Swift has its own set of sweet rules for its initializer.

Lets dig a little bit deeper into that.

C++: 
In C++03, there are constructors, obviously, and there is a rule that one constructor cannot call upon another. So all the member values have to be initialized again. Or a common function has to be built and both the constructors have to call that common function with filled in parameters if required. This seems like a minor inconvenience for smaller classes. But imagine that you have to type out the same for a huge list of members, as is the case in many commercial applications and games.

C++ Gurus understood the inconvenience and broke that rule in C++11. Now one constructor can call another constructor.  Whew!! Thank you ISO committee.

Since C++11 you can call other constructors and the term is coined as delegate constructors, what we call convenience initializers in Swift.

This is a convenience for C++11, because default parameters need not be added to the declaration of the delegate constructors, but only to the implementation.
for e.g

class MyPhone
{
  std::string ContactNumber;

  MyPhone(std::string Number):     ContactNumber(Number){ } 
   
  MyPhone(): MyPhone("000-000-000"){ }

}

If you had to use default value for the Number string argument, then you would have to do

MyPhone(std::string Number  = "000-000-000") in the declaration. This is inter-tangled with the project that might use this library code. Hence every time and anytime the default value changes, the client project has to be rebuilt.

But now with delegate constructors, it will not rebuild client code whenever default value changes. Because the default value is provided in the implementation in the form of delegate constructors. You might wonder, how might this make a difference in huge code base, where anyways, major changes only will be made which would require client project to be rebuilt. Well, every small step towards optimization counts rite? These small drops of performance boosters make up for the faster iteration cycles during development or later.

There are few caveats we have to remember.

1. In C++03, since there are no delegate constructors, when one constructor finishes execution, compiler considers the object to have been initialized. But in C++11 when any constructor finishes execution, compiler considers the object to have been initialized.

2. After C++11 you cannot delegate and initalize at the same time. For e.g if you call

MyPhone(): MyPhone("000-000-000") you cannot initialize other members in the same delegate constructor like this:

MyPhone(): MyPhone("000-000-000"), SecondMember("second"){ } //not allowed. 

3. Try catch is allowed in the delegate constructor.

MyPhone(): try MyPhone("000-000-000"){ 
   ------
  }
  catch(...){ 
    //handle exceptions

  }

Swift: 

So now coming to Swift, convenience init has to call atleast one

Swift has some seemingly out of the blue rules about its init, and the use of convenience in init() to create initializers. So after reading the official doc, and the tutorials, this is what pops out.

1. A convenience initializer must call any other initializer from the same class
2. A designated initializer can only call another designated initializer from its base class.
3. A convenience initializer must eventually call a designated initializer, otherwise compiler complains.
4. You cannot call one init() from another without making the calling init as convenience init, unlike C++ where extra keyword is not required to indicate delegation

init(ModelNumber: Int, color: BlockColor){
self.color = color;
self.ModelNumber = ModelNumber;
}

convenience init(ModelNumber: Int){
self.init(column: ModelNumber, color: BlockColor.random())
}


So basically almost the same semantics, except for a few. Initializer list in the constructor is not allowed in Swift, and swift initializers cannot fail and return nil. Seriously they are not allowed to fail as per Swift 2.0, instead they should throw the error out for the callee to handle explicitly.

convenience init(ModelNumber: Intthrows
  //handle ... 

}

//In the calling function

do {
    let str = try MyPhone(3433)
}
catch let error as NSError {
    print(error.localizedDescription)
}


There it is. tip of the iceberge. I am sure many more implementation mammoths are there related to the delegate constructors and the convenience initializers. For now this is a quick glance into both.


Saturday, April 9, 2016

Swifts' tuple and C++'s tuple

"Both have tuple, so why not compare and contrast them?" led to this write up.

Cutting right to the chase, here are the similarities and differences between swift and C++ tuple.

Basically both language tuples set out to achieve the same. To provide an anonymous structure like construct where zero or more heterogenous elements can be used without worrying about creating a class or structure. Used mainly with functions who have multiple elements to be returned.

You can read all about Swift tuple here and C++ tuple here  and lots of other online documents. So in this post I am not going to go into the syntactical differences. Rather, lets look at one single seemingly hidden usage difference keeping this blog post as crisp and clean as possible.

C++
In C++ some people thing using anonymous structs leads to long long hours of excruciating debugging, which could be reduced by  using clear, visible named structs.

The main irking factor regarding C++ tuple according to my humble opinion is the lack of programmer readable member names for each element.

For e.g If you have to access elements of a C++ tuple, you would have to do this:

#include

std::tuple GetCustomerInfo(unsigned long BillID)
{
   //retrieve bill details 
   return std::make_tuple(Name, Phone, Amount);
}

int main()
{
  auto cust = GetCustomerInfo(BillID); //assume BillID is valid
  std::cout << "Name:" << std::get<0>(cust) << endl; // usage of const numbers instead of proper member names is a well intentioned trap for longer crazier debugging hours. 
  std::cout << "Contact:'" << std::get<1>(cust) << endl;
  std::cout << "Amount:" << std::get<2>(cust) << endl;

}

Swift:
Now that C++ code is looked into, it should be relieving to know that swift eliminates that bothersome aspect by providing member names.

func GetCustomerInfo(BillID: UInt) -> (Name: String, Contact: String, BillAmount: Float)?{ //return optional tuple value
//retrieve values here
//if bill id is not found in the database return nil
return (Name, Contact, Amount);
}

//in another function

if let cust = GetCustomerInfo(BillID) { //if not nil, process value
print("Name: \(cust.Name) \n Contact: \(cust.Contact) \n Amount: \(cust.BillAmount)";
}




Tuesday, April 5, 2016

Swift's Dictionary and C++'s Unordered Map

I am not going to discuss and debate about which one is best. For me, both are tools to accomplish goals. So I am merely going to list out the similarities and differences between them.


Swift has dictionary and C++ has Unordered Map, similar to python's dictionary, in the sense of technical term and the key value pairs. Or similar to perls' hash as per semantics of key value pair. I am not going to discuss how they are all implemented internally. That is a whole new discussion for another day. For today, lets just look at the logical or syntactical differences and similarities.


What is?
Dictionary has key, value mapping. All keys belong to the same type. All values belong to the same type. Keys are unique, if a new key value pair is being added to this associative container and the key already exists as per the comparison logic, then the new values replace the old values. Old values will be lost forever.

Set:
Set the values is normally via the keys. Access the key directly, and set the value.

Swift:
var Dict = [Int: String]();
  1. Dict[16] = "sixteen" // to store the string value for a key value.Will add or replace to maintain uniqueness.

  or

  if let old = Dict.updateValue("sixteen", forKey: 16){ //updateValue returns old value as optional value if present. Otherwise returns nil. 
print("oldvalue \(old)");
  }

  //Remove an entry by doing this:

  Dict[16] = nil

  //Remove entry
  if let old = Dict.removeValueForKey(16) { //returns old value as optional value if exists
print("old value \(old)");
  }
  else {
print("old value did not exist");
  }


C++:
  1. unorderedmap[16] = "sixteen" // to store the string value for a key value.


Get:
Getting the values is normally via the keys. Provide the key directly, and Get the value. 

Swift:
  1. print(test[16]);
C++:
  1. cout << unorderedmap[16];

Sorted?
No. Both of them, dictionary, and unordered_map are not sorted. Hence the name unordered. 


Unique?
Yes. Both are. The keys are unique.

Speed:
Unordered associative containers such as dictionaries and unordered_maps are faster in accessing the values of the key because hash value of the key is calculated and values stored in buckets for faster access internally.


Initialize:
To initialize dictionary, you can either do 

  var Dict = [Int: String](); //empty dictionary

or

  var Dict = [16: "Sixteen", 14: "Fourteen"]//When you initialize directly, you do not have to specify type as long as the key and value types are consistent. Thanks to type inference

to initialize array of dictionaries:

var DictArray = [[String, String]](); //empty array of dictionaries

or

var DictArray: [[String, String]] = [ ["Name" : "Mark Timothy", "Address" : "address 1"],

                                      ["Name" : "Nathan Deneth", "Address" : "address 2"] ]
To initialize in C++11

std::unordered_map unorderedmap { {3, "three"}, {4, "four"} }; // Initializer list since C++11. Code gives error in Visual Studio 2012. Compiles fine in VS 2015


Looping through:
Swift:

for(key, value) in Dict{ //a for-in loop
print("\(key) : \(value)");

}

for key in Dict.keys { //Get only the keys
print("\(key)");
}
for value in Dict.values { //Get only the values. 
print("\(value)");
}

C++:

for(auto pair : unorderedmap){ // auto keyword from C++11
cout  << pair.first  <<  endl; // int
cout << pair.second; //string

}


Whatever covered here are mostly similarities. To find any difference I would have to dig deeper. That post would follow soon.








Friday, March 25, 2016

Swift: Guard ... what?????

At first I saw guard code sample, and I was like WHATT? WHY????

See in C++  there is only if (x) or if(!x) where x being an expression that can contain more than one expression in itself. So pardon me when I say WHY?????

Then after googling I found some nice articles, which explain why and when guard could be used efficiently.


So here goes my understanding:

Basically Guard is like If conditional statement except, it enters its scoped block only if the condition is false.

if guard x = x else { return; }

The code block inside else should either be a function that does not return anything, or it should move the control of execution outside the guard statement's code block. Meaning, only return/break/continue/throw can be used. Also one of these should be used otherwise be ready to face the compiler wrath with "/path/GameScene.swift:55:3: 'guard' body may not fall through, consider using 'return' or 'break' to exit the scope"

But why? Why can't I do if let x != nill { return; } ? This and the guard seems to be exactly the same.
Here is where nuances of the language comes into play.

Here are a few pointers regarding guard. I am going to list that out for you here.

1. Automatic unwrap of the optional 
If x is not nil, that is if x is valid, then if you use IF statement, then you would have to force unwrap it everytime after the IF statement using x!.function();

But if you use guard, then you need not force unwrap it, and can use it as a non optional parameter as x.function(); because guard preserves the context of x. Keeps it intact.

Say What????

So this would mean, when you use guard, you need not force unwrap the non optional parameter with !, but guard does that for you when exiting its scope. Which some people perceive as fine, and some not.

For e.g

var lastTick: NSTimeInterval? = 0


void update(){
     guard lastTick = lastTick where lastTick > 0 else {
        return;
    }

   lastTick.advanceBy(5); //automatically unwrapped by guard if exits, for you. How convenient and intuitive. Because if it was null, it would have returned from the function.
}

2. Guard is more like a graceful assert
Since guard scoped block executes only if the condition is not true, it can be looked upon as an assert, but instead of asserting, it would gracefully exit.

3. You need not check for the NOT condition. 
Yes that is a convenience. Instead of doing if (!x) you can do guard x.
for e.g 

var previousDate: NSDate?;


void update()
{
    guard let previousDate = previousDate else{
        return;
    }
}

In this, the condition which should be true is clearly evident to the same programmer after many years, or to a different programmer the same day.
     
4. Also to keep the code clean, instead of using nested conditions with if, you can guard them individually and exit from the scope if not met

Normally when lots of conditions have to be met as pre-checks in order for a code inside a function to run, it seems cleaner to do a guard for each, and exit from scope if not met.

This is the same as "Designed by Contract" software design terminology, that states all the preconditions have to be met before the main block of module could be executed.

Note: 
As an added bonus (I am kidding ofcourse) you can use guard on non optional values as well.

Thanks for reading this write up.


Monday, March 21, 2016

Closures in c++ vs that in Swift

Being a newbie in Swift language, I try to find correlation between the new language and the one I am familiar with.

One such technicality that I came across with is "Closures". It is there in both Swift and C++.



C++:
Closure in C++ are associated with Lambdas. There is a closure class, and a closure instance is created for each Lambda. The closure class is unique for each lambda. The class has member function to execute the code provided in lambda.

For e.g

auto C1 = [x](int y){ return x * y > 55; }

C1 is a copy of the closure of the lambda.

During compilation, closure class is created. During runtime closure instance is created.

There are two default capture modes in C++11. By reference and by value. It simply means, how the arguments are going to be passed in to the lambda class's member function. The memory is taken from the context in which they are defined.

Beware of dangling reference in case of by reference capture mode.

Sorting closure:

1. std::vector names = {"Damien", "Bob", "Alex", "Mari", "Dexter"}; //list initialization

std::sort(names.begin(), names.end(),[](const std::string& a, const std::string&b){ return a.compare(b) > 0; }// closure will compare a and b (two strings from the names' list passed as arguments, and return true to create backwards order.

The argument type has to be specified in the argument list in C++11. Auto variable cannot be used. Polymorphic or generic lambdas are part of C++14 though.

In Swift though, it can infer the type from the context, and the argument type need not specified . See e.g 4.

Swift:

Closure in Swift basically is a block of code that performs a function. It can be used as arguments.

Closure in Swift also has capture mode (by reference) of any variable or constant from the context in which they are defined.

So essentially seems to be same as that of C++. But. But. read below to know the nuance of Swift Closure.

Sorting closure:

2. let names = ["Damien", "Bob", "Alex", "Mari", "Dexter"];
func backwards(s1: String, _ s2: String) -> Bool { return s1 > s2; } // comparison function returns bool

var reversed = names.sort(backwards);
print(reverse);

or
3. reversed = names.sort( {(s1: String, s2: String) -> Bool in return s1 > s2 ; } )

or
4. reversed = names.sort( { s1, s2 in return s1 > 2 ; } ) // because Swift is cool to infer the argument's type from the list type.

or
5.  reversed  = names.sort( { s1, s2 in s1 > s2; } ) //because Swift can infer the return type from the code. So return keyword is not required.

or
6. reversed = names.sort( { $0 > $1 } ) //because Swift can use shorthand argument names.

or
7. reversed = names.sort(>) //because String has a > function that does the comparison. Swift will infer that you want to use string specific comparison operator.

-The end. No more shortcuts.



Saturday, January 30, 2016

C++11 and initializer list

This post is about one example of using initializer list in C++.

Imagine a parent child relationship between two classes.
Parent has a child (obviously).
Child has a pointer back to the parent.
Now the Child is not a pointer in the parent class, but a member object.

Here a simple and easy way to use initializer list in order to pass parents' "this" pointer to the constructor of the Child class

Class Child
{
private:
Parent* p;

public:
Child(Parent* p1): p(p1){}
};


Class Parent
{
private:
Child c;

public:
Parent(): c(this){}
};

This is perfectly fine. One can use "this" pointer inside the initalizer list or constructor as long as the object to which "this" pointer has been passed on to (i.e the child object), does not use the uninitialized members or virtual functions of the parent class.

For e.g Child class's constructor should not use any uninitialized pointers or members of parent class. Child class' constructor should not call any virtual function as well because one might expect the child class's virtual function definition to  be invoked. But it would in fact invoke the parent class's virtual function definition if any because the child class's virtual function will not be visible inside the child class's constructor.

Hence, uninitialized members are not yet initialized, and virtual functions would result in calling the base class function instead of derived class function.