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(){


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.

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"){ 
    //handle exceptions



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 {

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.

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:


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;


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 the values is normally via the keys. Access the key directly, and set the value.

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


  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");

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

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

  1. print(test[16]);
  1. cout << unorderedmap[16];

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

Yes. Both are. The keys are unique.

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.

To initialize dictionary, you can either do 

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


  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


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:

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


for key in Dict.keys { //Get only the keys
for value in Dict.values { //Get only the values. 


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.