Collection Type, Sequence Type & Indexable Type

This is for Swift Version 2.2 & earlier. I will be adding the snippet of code for the changes the Swift 3.x have introduced.

What are the Collection Type & Sequence Type Protocols?

The Collection Type, Sequence Type & Generator Type Protocols define rules that govern how different data structures or collections of data can be used, interacted with and operated within the Swift programming language. The CollectionType is a special case of the SequenceType.

Why do we need such Protocols?

Lets take the example of the Swift For-Loop.

var arrOfStrings : [String] = [String]()

arrOfStrings.append("Jill")
arrOfStrings.append("Jack")
arrOfStrings.append("John")
arrOfStrings.append("Jane")

for name in arrOfString
{
     print("The name is \(name)")
}

Now, if we have created our own data type. We would not be able to use the above for-loop as it would not conform to the … type protocols. The for-loop is expecting a data structure that acts and behaves in a way that is governed by the … protocols.

Just like the for-loop example above there are many other features within the Swift Programming Language that expect data structures to act and behave in a particular way. By designing our data structures to conform to these protocols we can make the easily compatible with the existing code and language features out there.

How do we use these protocols for our own data structures?

First we need to decide what kind of collection are we making. For the sake of this example I will create a Custom Stack.

class CustomStack<Element>
{
    var data : [Element] = [Element]()

    func push(Element newElement : Element)
    {
        data.append(newElement)
    }

    func pop() -> Element
    {
        return data.removeLast()
    }
}

The above code is very simple for the purpose of this exercise. Its a stack. Which is internally really an Array. It has functions to push data and pop data. We are now going to convert this type to a collection to conform to the CollectionType protocol.

Implementing the Indexable Protocol methods

As a first step we are going to make our CustomStack conform to the Indexable Protocol.

extension CustomStack : Indexable
{
    //INDEXABLE PROTOCOLS
    typealias Index = Int

    var startIndex : Int
    {
        return 0
    }

    var endIndex: Int
    {
        return (data.count - 1)
    }

    subscript (position : Int) -> Element
    {
        return data[position]
    }
}

The above change makes the data structure conform to the Indexable protocol. This is a requirement for it to be of type CollectionType. In order to conform to the Indexable protocol we need to implement a few computed properties. Let us look at the changes

typealias Index = Int

This line informs the system that the Indexing type for my data structure is an Int.

var startIndex : Int
{
    return 0
}

var endIndex: Int
{
    return (data.count - 1)
}

The next 2 are computed properties. Each provides the implementation of the startIndex  and endIndex properties. Note that the type for both is Int as we have declared the Index type earlier as Int.

subscript (position : Int) -> Element
{
    return data[position]
}

The last implementation is of subscript. This provides the implementation to access an Element from the Stack using the Subscript operator.

Implementing the Sequence Type Protocol

Next we will implement the Sequence Type Protocol methods.

extension CustomStack : SequenceType
{
    typealias Generator = AnyGenerator<Element>
    
    func generate() -> Generator
    {
        var index = 0
        
        return AnyGenerator(body: {() -> Element? in
            if index < self.data.count
            {
                let res =  self.data[index]
                index += 1
                return res
            }
            return nil
        })
    }
}

Let us examine this code line by line.

typealias Generator = AnyGenerator<Element>

Objects of type Generator allow us to navigate through our collection. Quite like how iterators  work in C++. This line specifies the type to be AnyGenerator for Elements.

func generate() -> Generator

Next we start the implementation of the generate function. This is required as part of the SequenceType protocol.

var index = 0

This index variable is used to track the element that is currently being accessed.

return AnyGenerator(body: {() -> Element? in
            if index < self.data.count
            {
                let res =  self.data[index]
                index += 1
                return res
            }
            return nil
        })

The return statement is the main statement. Here we are creating an object of type AnyGenerator. As an argument to the constructor call we are passing in a closure that will be used to iterate through the sequence. Note that the closure captures the index variable and holds a reference to its value even though we have left the original function.

Implementing the Collection Type Protocol

Next we will implement the Collection Type Protocol methods. We don’t really need to implement a lot in order to conform to the CollectionType protocol. In fact, if we just conform to the CollectionType protocol and use the implementations of the previous 2 extensions we should be just fine. However, for the sake of demonstration we are implementing the subscript functionality within the CollectionType.

extension CustomStack : CollectionType
{
    typealias SubSequence = CustomStack<Element>
    
    subscript (bounds: Range<CustomStack.Index>) -> CustomStack.SubSequence
    {
        let newStack : CustomStack<Element> = CustomStack<Element>()
        
        for i in bounds.startIndex...bounds.endIndex
        {
            newStack.push(Element: data[i])
        }
        return newStack
    }
}

Let us look at the code line by line.

typealias SubSequence = CustomStack<Element>

Again, as before this line indicates that the SubSequence type is actually a CustomStack.

subscript (bounds: Range<CustomStack.Index>) -> CustomStack.SubSequence

Here we start the implementation of the subscript functionality.

let newStack : CustomStack<Element> = CustomStack<Element>()
        
for i in bounds.startIndex...bounds.endIndex
{
     newStack.push(Element: data[i])
}
return newStack

The rest of the code is the implementation of the subscript range behaviour. One can have different implementations to achieve the same result.

CollectionType Video

Conclusion

As we can see, by designing our data structure to conform to a particular set of protocols. We have made it possible for our data structure to take advantages of the different features, functionalities and even API’s available within the Swift Language and the Frameworks used as a part of iOS, macOS, watchOS & tvOS development.

Clarifying Swift & Objective-C

swiftApple made a surprising announcement at the recent WWDC held between June 2-6 2014. While everyone was looking forward to the launch  of the new OS for both the Mobile as well as Mac platforms, Apple also announced a new programming language for developers. SWIFT.

It was described as Objective-C without C. Over the past few months I have gone over the features of the language & even converted many of the apps into Objective-C. While the initial learning curve is there, it is a fairly easy language to pick up. I will be going over a few interesting features of the language in this article. But what I will also be touching upon is the future & relevance of Objective-C.

Reduction in Lines of code: One of the first things that you will notice once you start programming in Swift is the reduction in the number of lines of code. Swift does away with the long syntax which you find in Objective-C. This makes the code look a lot more compact & less intimidating.

Lets take the example of creating an object in Swift & compare the syntax with that of Objective-C

Objective – C version: NSString *myString = [[NSString alloc] initWithString:@”This is a string”];

Swift version: var myString : String = String(“This is a string”)

As we can see, there is a great deal of simplicity that comes along. Reduction in the number of lines of code is of great importance to software developers. This means more compact code & improves readability. However, this comes at a price. While Objective-C code was more elaborate & did use many more lines of code it was far easier to understand by simply reading through it. In case of Swift the code will have to be complemented with details comments about what it does.

Single File: Another new feature there in Swift is the lack of header files. People coming from a Java background would find this familiar. The declaration of classes & implementation of its functions is done in .swift file now. This removes the necessity of having to import various header files. In case, certain frameworks need to be used all that needs to be done is to import that framework at the top of the file.

import framework

Replace the keyword framework with the name of the framework you wish to include.

Mixed Language Programming: Unlike Objective-C, Swift does not work well with other languages. In fact, Swift only works with Objective-C. So if you have any API’s or pieces of code that you have written in C or C++, you will have to create Objective-C wrapper classes for that C/C++ code so that you can incorporate it into your project.

This means that Objective-C is not going to be deprecated any time soon. Also, it will be equally important to learn Objective-C & can’t be ignored by people.

COMMON QUESTIONS:

– I already know Objective-C should I also learn Swift?
There is no pressing need to immediately learn Swift, though it would be a good idea to learn it anyways. None of the apps you have already made will stop working. However, you may come across code written in Swift or would need to incorporate programs written in Swift, so having knowledge of the same would be a good idea.

– I don’t know Swift or Objective-C which should I learn?
Again, as in the previous question knowing both is a really good idea. If you are confident that you will be making apps using Swift only, then you can learn just that for starters. If you feel that there is a good chance of having to read/modify or write Objective-C code then learning Objective-C before Swift makes more sense.

CONCLUSION: Swift is a very easy to use language & will sit nicely on familiar eyes. A lot of the code that will be written in the coming apps will definitely use Swift. However, this does not mean the end of the road for Objective-C. Nor does it mean that Objective-C will become redundant or obsolete. A developer can choose to use any of the languages to make the app. It will be nice for a new developer to first learn Objective-C & then move on to Swift as it will give the user a more all round understanding of the entire development framework .

 

C++ in iOS – 2

Continuing from the previous post. This one will look into a working example for the same. The code used here is pretty trivial. It is organized in the following sets of files. A c++ header file which contains the declaration of a class. A c++ implementation file (.cpp) where the member functions are implemented. An Objective-C++ header file which holds the C wrapper struct & an Objective-C wrapper object. An Objective-C++ implementation file (.mm) which implements the C struct & all the member functions for both the C struct as well as the Objective-C class.

CppStruct.h


#include <string>
class MyObject
{
     public:
          std::string getName();
          void setName(std::string tempName);
          MyObject();
      private:
           std::string name;
 };

CppStruct.cpp

#include "CppStruct.h"
#include <string>
#include <iostream>

std::string MyObject::getName()
{
     return name;
}

void MyObject::setName(std::string tempName)
{
     name = tempName;
}

MyObject::MyObject()
{
     name = "NIL";
}

CppStructWrapper.h

struct PersonWrapper;

@interface CppStructWrapper : NSObject
{
     struct PersonWrapper *obj;
}

-(void) makeAPerson;
-(void) setName:(NSString *) personName;
-(NSString *) getName;
@end

CppStructWrapper.mm

#import "CppStructWrapper.h"
#include "CppStruct.h"
#include <string>

@implementation CppStructWrapper

struct PersonWrapper
{
     MyObject *personObj;
     std::string getName();

     void setName(std::string tempName);
     PersonWrapper();
};

std::string PersonWrapper::getName()
{
     return personObj->getName();
}

void PersonWrapper::setName(std::string tempName)
{
     personObj->setName(tempName);
}

PersonWrapper::PersonWrapper()
{
     personObj = new MyObject;
}

-(id) init
{
     self = [super init];
     if(self)
     {
          obj = nil;
     }
     return self;
}

-(void) makeAPerson
{
     obj = new PersonWrapper;
}

-(void) setName:(NSString *) personName
{
     std::string temp([personName UTF8String]);
     obj->setName(temp);
}

-(NSString *) getName
{
     NSString *str = [[NSString alloc] initWithUTF8String:obj->getName().c_str()];
     return str;
}

@end

ViewController.m

//this code could be anywhere I have put it inside the ViewController.m within the init message.
#import "ViewController.h"
#import "CppStructWrapper.h"

-(id) init
{
     self = [super init];
     if(self)
     {
          CppStructWrapper *obj = [[CppStructWrapper alloc] init];
          [obj makeAPerson];
          [obj setName:@"ABC"];
          NSString *str = [obj getName];
          NSLog(@"%@",str);
     }
     return self;
}

 

C++ in iOS

As we know there are many libraries out there that are written in C++. Now it would be really nice & handy if we could integrate them into our iOS App. There are many blogs out there that discuss the same.

I found this particular article quite good: http://philjordan.eu/article/strategies-for-using-c++-in-objective-c-projects

The article talks about the PIMPL approach. There is another link to the same related article by the same author:http://philjordan.eu/article/mixing-objective-c-c++-and-objective-c++

The following is one approach towards integrating C++ API into your App. To make things simpler there is a lot of wrapping to do.

Declare your class in the C++ header file as is.

Now to use this class in Objective-C we need a wrapper. To create this wrapper go ahead & make a simple Objective-C class which inherits from NSObject. But once you are done making, rename the extension of the implementation file from .m to .mm, this makes it an Objective-C++ file.

In this file we will be forward declaring a struct which will eventually wrap our C++ class. Create a pointer variable of the struct to be a member of the Objective-C++ class.

Implement the struct in the .mm file to have an object to our c++ class & some member functions to access it. Remember a struct is a valid “C” type. We have created an Opaque struct, but in the implementation it is ok to have member functions (which is allowed in C++). So this struct acts as a bridge between C & C++.

Once you have done this you are set.

The flow for the entire code will be in the form

IOS App Code -> Your Objective-C++ Wrapper -> Your struct wrapper -> Your C++ class in the header file

Continue reading

Attention to Details

One of the most defining things to come out of the Mobility Development revolution is the renewed focus on the User Experience. 

User experience is not a new concept. It has been there around since the beginning. The introduction of GUI (Graphical User Interfaces), & the mouse was one of the first steps taken towards making the users experience better. Its the first thing that people notice. At the launch of a new product people are curious to know how a particular product will look like.

Its the one thing that people say about Apple’s products. “They just look good”. Different companies have tried in their own way to make the User Experience a wonderful experience. But just what makes it click. 

As users we are able to tell when a product looks great & when it doesn’t or lacks in some aspect. This fact is highlighted even more in Mobile Devices. Attention to Detail.

This is most visible in Gaming. Introducing the effects of gravity to give a realistic feel, making sure objects move in the manner & direction in which people expect upon collision, or just moving the screen elements in accordance to the phone. Many of these changes are subtle. We as users would not even realize these things. But we will know for sure if they are absent. It takes some degree of effort to get the attention to detail in place.

A point to note. Im many cases, adding these small features may not improve or enhance the performance/utility at all. But they add a huge advantage in that it gives the user a feeling that he/she is using a great product. Putting in that little extra effort does have an additional value.

BOTTOM LINE: Put in the extra effort to add those nice features to your app. Either something that makes the app look & feel more realistic &/or something that increases the visual appeal of the app.

C++ in todays Day & age

Anyone entering the programming industry at this point in time will be spoilt for choice. There are a whole host of Operating Systems & machines available. The choice caters to all budgets, backgrounds & likes. There is a huge choice in programming languages too. Although some programming languages like C# & Objective-C force users to pick the OS. Others like C,C++,Java don’t place such constraints on the users.

Now there are many rankings available for which programming language is the best. Here are a few links for the same:

http://spectrum.ieee.org/at-work/tech-careers/the-top-10-programming-languages

http://www.siliconindia.com/shownews/10_Most_Popular_Programming_Languages-nid-106520-cid-2.html

The fact that C & C++ are still extremely popular would surprise a lot people. The fact is that a lot of languages that came after these 2 still derive many concepts & features from C & C++. They are must know languages for anyone venturing into the world of programming. Once a person learns these 2 languages it is very easy to branch out & leaner virtually any other language.

Other than C & C++ the other language that is most popular is Java. A lot of people like Java because of the platform independence that it offers. C & C++ are not platform independent. However, they are cross platform languages. Which means that you can develop applications using C & C++ on virtually any OS.

A list of major applications that use C++: http://www.mycplus.com/featured-articles/top-10-applications-written-in-c-cplusplus/

At the end of the day, the decision as to which language is good for developing applications depends on a lot of factors. Discarding C++ early on is not a wise choice. Simply because it is very relevant even today. It has a large set of libraries & is thoroughly time tested.

Bottom line: Do consider using C++, its a highly relevant language & a good place to start your programming career or to make a career out of.