Porting to Swift from Objective-C

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

Finally its time to take swift language on a serious note. All the examples in the blogs have been converted to swift language. With me having worked with a bit of Java(Android), Python and javascript, I thought i could speed up my learning by porting one of the existing Objective-C project where I can touch upon all most often used elements

Note: This is not a Introduction to Swift programming post. I would suggest you read this, if you are an seasoned Objective-C developer and want to see a sneak peak of what Swift has to offer you.

In this post, I will be walking you through the differences/modifications I found when porting from Objective-C to Swift ( Don’t mistake this with Convert-to-swift feature in Xcode). The differences would be more of a design / semantical in nature and not one-to-one mapping of syntax. Fo e.g. I will not say that to declare a class, you use class keyword  in swift instead of @interface in Objective-C. These differences are nothing new in any object oriented languages. However, Objective-C being dynamic typed language, It need a perspective change to program in swift, especially if you have been coding in Objective-C for a long time. 

 

#1 You don’t have to subclass all your classes from NSObject

“NSObject is root of all the classes. It provides methods for things like alloc, init and release. Objective-C is all about sending messages to other objects – so NSObject exists to provide this basic functionality” – from http://stackoverflow.com/a/12991946/623569

#2 Immutability is let, Mutability is var. Always start with ‘let’

Its takes time to get used to using let or var keywords to declare a variable, and it takes more time to know that mentioning Data type is not mandatory. But the key thing, is swift compiler does not complain if you declare a variable using var and does not modify it. This means, that you will end up with swift compiler generating a lot of code to support mutability of these variables which directly affect overall performance.

@iDeekshi got me a nice tip – Start with declaring a variable as let and let the compiler complain when it is mutated.

#3 Yet another block syntax 

It took a lot of time for me to practice the block syntax in Objective-C. In swift, it looks like I am back to square one. Flower braces ‘{‘ starting before the parameter declaration, and writing the function definition after ‘in’ keyword is something I am still getting used to.  Here is it how it looks:

{

[capture list] (parameters) -> Return Type  in

<code>

..

..

#4 Use === to compare two object pointers

Comparing two object pointers studentObj == otherStudentObject will now need to be studentObject === otherStudentObject. Its a good move.

#5 You no longer need NSDictionary to send more than one value. Swift introduces Tuples to return multiple values

This has been a long time ask from me. I am glad we finally have it. You can create a type with just defining all the values and its types in a parenthesis as show below

func getMinAndMax( numbers : [Int] ) -> (min : Int, max : Int ){ 

   var max = numbers[0] , min = numbers[0] 

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

 ..

 ..

return (min,max)

}

 

#6 Initialize all your variables in the class before calling super init.

class Person{

var name : “”

init() {

name = “<unknown>”

}

}

class Teacher : Person{

var subjects : [String]

init() {

 //we have to initialize the subjects before calling super init

subjects = [“English” , “Kannada”]

super.init()

}

}

This is not the complete list. I have only picked those which I thought had a striking difference from what we are used to while programming in Objective-C. 

Let me know your experiences while porting Objective-C to swift code through comments.

Happy Coding 🙂

10000 HITS!!

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

Hey Folks,

This blog just got its 10,000 hit and thank you each one you who have shown good support towards this blog. I think this is just the beginning. Just to give some stat on this short journey, the most liked posts in this blog are

Efficient Memory Handling in UIViewController-Part 1

iOS Open Folder Animation

And Apologize for not updating this blog for past 5 months, I have bee caught up in too many things viz ICC Cricket World Cup 2011(hey India Won it 🙂 ), IPL (RCB made it to Finals) and shifting focus to Android OS.

And lately, burnt my fingers by updating iOS 5 Beta onto my iPad ( unofficially the iPAd 1), and after experiencing its flaws (I don’t like it being tagged as BETA) tried to restore it to 4.3.3 successfully( in an ugly way ) but none of the third party apps are working anymore.

If you are planning to upgrade to iOS 5 BETA, then I would say spend your valuable time onto something else, and if you are still want to do, Make sure you BACKUP YOUR DEVICE before attempting it.

Will get back to you sooner.

All the Best!!

Happy Coding 🙂

Autocapitalizing string

This code snippet requires RegexLite Library.Check here

#import “RegexKitLite.h”

@interface NSString(RegExAdditons)

 

+(NSString*)autocapitalizedStringForString:(NSString*)inString;

 

@end

 

 

@implementation NSString(RegExAdditons)

 

+(NSString*)autocapitalizedStringForString:(NSString*)inString

{

NSMutableString *completedString =[NSMutableString stringWithString:@””];

if( inString && ![inString isEqualToString:@””])

{

 

/* Regular Expression for extracting the words in a sentence*/

NSString   *regexString  = @”(\w*)”;

completedString =[NSMutableString stringWithString:inString];

 

NSUInteger totalLength = [completedString length];

NSUInteger currentIndex=0;

 

/* With the help of RegexLite, we extract all the words in the given string*/

NSArray * components = [inString componentsMatchedByRegex:regexString];

int index =0, count = [components count];

 

for( ; index < count;index++) {

 

NSString *matchedString = [components objectAtIndex:index];

 

NSUInteger matchedStringLength = [matchedString length];

if( matchedStringLength>0) {

unichar character=;

[matchedString getCharacters:&character range:NSMakeRange(0, 1)];

 

/* if the first character of the word is a ASCII character, then change the letter to its Upper Case version*/

if( isascii(character) ) {

 

/*Find the Location of the First letter of the matchedString within the given string*/

NSRange range = [completedString rangeOfString:matchedString options:NSLiteralSearch range:NSMakeRange(currentIndex, totalLength-currentIndex)];

 

if( range.location != NSNotFound) {

 

/*replace the first letter of the matched string to its upper case version*/

[completedString replaceCharactersInRange:NSMakeRange(range.location, 1) withString:[NSString stringWithFormat:@”%c”, toupper(character)]];


currentIndex+=matchedStringLength;

}

}

}

}

}

return completedString;

}

@end