Abhishek Neb

Objective-C vs Swift (Part -1)

Objective-C vs Swift

Few years ago, when I started developing iOS and OS X native applications, “Objective-C”  was the primary programming language for developing native applications.  Finally, Apple has now provided one more programming language i.e. “Swift” for us developers.

When Apple introduced Swift they shared some key features like:

Swift

 

Swift is now also faster than Objective-C as shown by these benchmarks:

Complex Object sort                     RC4 Encryption

 

Now you may have few questions in your mind. If you are new to iOS and OS X application development then you might be thinking about

  • Which programming language should I learn to develop iOS and OS X applications “Objective-C” or “Swift”?

If you are already a Objective-C programmer then you might be thinking

  • Should I switch to “Swift” to develop applications? If I switch then what would happen to my old code, patterns and practices which I developed over the years in “Objective-C”.

So which of these languages is faster, interactive, reliable, and more fun to work with?

Lets dive into their history and differences!

Origins

  • Objective-C was developed in early 1980’s whereas, Swift development started in 2010 and first introduced in 2014.

  • Objective-C was created primarily by Brad Cox and Rengktt at their company Stepstone whereas,  Swift was created by Chris Lattner at Apple Inc.

  • Objective-C used for NeXTSTEP operating system by Next, from which OS X and iOS are derived whereas,  Swift is designed to work with Apple’s Cocoa Touch Frameworks and Cocoa and used for iOS, OS X and watchOS development.

  • Objective-C is a general purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Objective-C is a strict superset of C, means it uses all the functionality of C. It provides language-level support for object graph management and object literals while providing dynamic binding and typing, deferring many responsibilities until runtime which makes it powerful whereas, 

    Swift is a multi-paradigm, compiled programming language. It builds upon best of C and Objective-C, as per Apple it is Objective-C without C. Swift gets its ideas from many other programming languages like Objective-C,  Ruby, Python, C#, Haskell, Rust, CLU and many more. Swift provides safe programming patterns and make programming easier by adding many modern features. Swift is flexible, adopts readability of Objective-C’s named parameters without compromising with the power of Objective-C’s dynamic object model.

Swift also has high-level language features like:

Swift Fetaures

 

Basics

  • The canonical example i.e. “Hello World!”

Objective-C

NSLog(@"Hello World!");


Swift

print("Hello, World")

In Swift, you don’t need to import a separate library for functionality like input/output or string handling. Code written at global scope is used as the entry point for the program, so you don’t need a main() function. You also don’t need to write semicolons at the end of every statement.

  • Variables and Constants

    Variables are those whose value can be changed once it was set whereas Constant are those whose value remains fixed and its value cannot be changed once its set.

    Objective-C
    Variable can be type of BOOL, NSInteger, double, id, NSString, NSArray etc.

    NSInteger myFirstVariable = 10;  // or you can also use C int, like this
    int myFirstVariable = 10;
    
    NSString *myStringVariable = @"My String Variable”;
    
    CONSTANTS 
    
    // Constants.m
    static NSString * const kMyFirstConstant = @"My First Constant Value";
    
    OR
    
    // Constants.h
    extern NSString * const kOtherWayFirstConstant;
    // Constants.m
    NSString * const kOtherWayFirstConstant = @"My Other way first constant value";
    


    Swift
    Variable can be type of Bool, Int, Double, String, Array etc.
    If you provide an initial value at same time while defining a constant or variable, Swift can always tell you the type that constant or variable is going to infer

    // Infer type
    var myFirstVariable = 10
    // Type Annotation
    var myStringVariable : String = My String Variable
    

    Now you might be thinking when there is no semicolon how can i declare multiple variables or constants on a single line?

    Here is your answer just separate them by commas like mentioned below:

    var red, green, blue: Double
    var x = 0.0, y = 0.0, z = 0.0

     

    If a value is never going to change in your code always declare it as constant

    let kFirstSwiftConstant = "My First Swift Constant"
    let kMaximumLoginAttmepts = 3
    

     

    In Swift, constants and variables can contain almost any characters including UNICODE also. For e.g.

    letπ = 3.14159c
    var ?? = "This variable is dog and cow"
    


    Type Safety and Type Inference

    Swift is a type safe language which catches your errors while compiling your code. A type safe language means you should be clear about the  types of values your code can work with. If your code expects a String, you can’t pass any other except string like bool, double, etc.

  •  Properties : It is used to avoid writing setter or getter methods. It is a way for objects to access or inspect any change in state of any other object’s underlying data.

    Objective-C

    @property (nonatomic) NSMutableArray *mutableItems;
    @property (nonatomic, strong) NSArray *immutableItems;
    @property (nonatomic, weak) id<ClassProtocolDelegate> *delegate;
    Lazy Properties
    // In .h file
    @property (nonatomic) MyProcessor *myProcessor;
    // In .m file
    - (MyProcessor *)getMyProcessor {
         if(!_myProcessor) {
            _myProcessor = [MyProcessor alloc] init];
           }
       return _myProcessor;
    }
    


    Swift

    var mutableItems:Array<Int> = [1,2,3,4]
    let immutableItems = [10, 20, 30, 40]
    weak var delegate: ClassProtocolDelegate?
    
    Lazy Properties
    @lazy var processor = MyProcessor ()
     var processorPower:Int {
     get {
      return processor .power
     }
     set(newPower) {
      self.processor.power = new.power
     }
    }

    Now you might be thinking what is this question mark (?) doing…
    These are known as Optionals – means either holds a value or absence of value. It is very similar to using nil with pointers in Objective-C. We can also add an exclamation mark (!) after an optional value to force the unwrapping of its value. These are safer and more expressive then nil pointers.

    As mentioned above Swift is a type safe language, Optionals is one of the example for same.

  • Methods Objective-C

// Method without parameter
- (void)myMethod 
{
  // Do Something
}  

// Method with single parameter
- (void)myMethodWithValue:(SomeType)value
{
  // Do Something with value
}  

// Method with multiple parameters
- (void)myMethodWithFirstValue:(SomeType)value1 secondValue:(AnotherType)value2 
{
  // Do Something with value1 and value2
}  

// Get some value
- (int)getSomeValue
{
  // Get some value
  return 100;
}

 

Calling any method

[myObject myMethod];
[myObject myMethodWithValue:paramValue];
[myObject myMethodWithFirstValue:firstParamValue secondValue:secondParamValue];
[myObject getSomeValue];

 

Swift

// Method without parameter
func myMethod 
{
  // Do Something
}
 
// Method with single parameter
func myMethodWithValue(value) 
{
  // Do Something
}
 
// Method with multiple parameters
func myMethodWithFirstValue(value1, secondValue:value2) 
{
  // Do Something with value1 and value2
} 

// Get some value
func getSomeValue()->Int
{
  return 100
}

 

Calling any method

myObject.myMethod()
myObject.myMethodWithValue(paramValue)
myObject.myMethodWithFirstValue(firstParamValue,secondValue:secondParamValue)
myObject.getSomeValue

That’s it for now. I think with this post, you might have got some basic idea about some differences between Objective-C and Swift. I’ll be back soon with the second part of this series with more details.

Please let me know your feedback or questions in the comments below!