Basic syntax comparison: Objective-C vs. Swift

Objective-C vs. Swift

Swift is the new modern, save, fast and interactive programming language for iOS, OS X, tvOS, and watchOS. It’s really easy to learn, especially if you are coming from Objective-C or Javascript background.

Many people are skeptic when it comes to “switching” from Objective-C to Swift, but I didn’t have any problems with it. My experience learning Swift was really positive, as I managed to fully adapt in just 2 weeks. In the first 2 months, I have finished 5 small/medium sized projects and all without any problems.

In this tutorial, I will cover some of the most common data types used in Objective-C and Swift.

NSArray

Objective – C

NSArray *array = [[NSArray alloc]initWithObjects:@"string1",@"string2",@"string3", nil];

Swift

let array = ["string1","string2","string3"];

NSDictionary

Objective – C

NSDictionary *dict = @{@"key1":@"value1",@"key2":@"value2",@"key3":@"value3"};

Swift

let dict = ["key1":"value1","key2":"value2","key3":"value3"]

NSString

Objective – C

NSString *customString = [NSString stringWithFormat:@"Writing some random string at %@",@"theappspace.com"];

Swift

let theappspace = "theappspace.com"
let customString = "Writing some random string at \(theappspace)"

NSNumber

Objective – C

NSNumber *num = [NSNumber numberWithInteger:5];

Swift

let num  = 5

NSDate

Objective – C

NSDate *date = [NSDate date];

Swift

let date = NSDate()

 


Mutable data types: 

  • Objective-C – Adding NSMutable prefix to the data type (NSMutableArray *someArray, NSMutableDictionary *someDict)
  • Swift – Adding var instead of let (var someArray, var someDict)

Immutable data types:

  • Objective-C – Adding NS prefix to the data type (NSArray *someArray, NSDictionary *someDict)
  • Swift – Adding let instead of var (let someArray, let someDict)

I really love the shortened syntax compared to the Objective-C one, where the function naming is really long and many times annoying. On the other hand, Objective – C is much more stable than Swift, mainly because it has been on the market for the much longer period.

Good luck!

Leave a Reply

Your email address will not be published. Required fields are marked *