Difference between Objective C and Swift
Why Objective-C?
The Objective-C language was chosen for a variety of reasons. First thing is, it’s an object-oriented language. The kind of functionality that’s packaged in the Cocoa frameworks can only be delivered through object-oriented techniques. Second is because Objective-C is an extension of standard ANSI C, existing C programs can be adapted to use the software frameworks without losing any of the work. Because Objective-C incorporates C, you get the benefits which are in C when working within Objective-C. You can choose when to do something in an object-oriented way and when to stick to procedural programming techniques.
As compared to other object-oriented languages based on C, Objective-C is very dynamic.
Why Swift?
Swift basically uses for a general-purpose, multi-paradigm, compiled programming language developed by Apple Inc. for iOS, tvOS, MacOS, watchOS etc. Swift is designed to work with Apple’s frameworks like Cocoa and Cocoa Touch and the large body of present Objective-C (ObjC) code written for Apple products.
Swift supports the core concepts which made Objective-C flexible.
Main Difference in Swift and Objective-C
- Optionals
- Control Flow
- Type Inference
- Functions
- Guard and Defer
- String Manipulation
- Functional Programming Patterns
- Enumerations
- Tuples
- Do Statement
- Optionals
Optionals functionality is not provided in C or Objective C. In Swift allow functions which may not always be able to return a meaningful value to return either a value encapsulated in an optional / nil. In C and Objective-C, we can already return nil from a function that normally return an object, but we don’t have this option for functions which are expected to return a basic type such as int, float, or double etc.
let a = “3.14”
let b = Float(a)
print(b) // Optional(3.14)
In Above example float function returns optional value contains int float value 3.14 . If we assign some string like “abc” it returns nil value
let a = “String”
let b = Float(a)
print(b) // nil
In Objective-C, if you call a method on a nil pointer, nothing happens. No compile errors, no runtime errors, nothing.
- Control Flow
As we know in C or like-C language it is familiar with the use of curly braces({}) to delimit code blocks.
In Swift, we need to use curly braces strictly or it’s a law!
if a == 0 {
print(“Bitware”)
}
This will gives an error in the swift!
if a = 0
print(“Bitware”)
Unlike Objective-C, Swift treats curly braces are mandatory for if, for, while, and repeat etc. Statements
- Type Interface
Swift allows type safety in iOS development. Once a variable is declared with a particular type, its type is static and cannot be changed.
- Tuples
tuples are values which store groups of other values. Like an array, it doesn’t save value of the same type
var tuples:(String, Int) = (“Abc”, 27)
print(tuples.0, tuples.1)
- String manipulation
In swift string manipulation in improved as compare to Objective-C. String concatenation is very simple
// Swift:
var str = “String One”
str += ” and string two”
// Obj-C:
NSString *str = @”String one”;
str = [NSString stringWithFormat:@”%@ and string two”, str];
- Guard and Defer
Guard stops program flow if a condition is not met or match.
Defer is use when we want to be executed only when the program leaves the current scope.
- Functional Programming Patterns
Swift include a number of functional programming features, such as map and filter, which can be used for any collection which implements the Collection Type protocol.
Example:
let a = [4, 8, 16]
print(a.map{$0 / 2})
// [2, 4, 8]
let a:[(name:String, field:String)] = [(“John”, “iOS”), (“Sam”, “web”), (“Paul”, “PHP”)]
let b = a.map({“Field \($0.field) (\($0.field))”})
// [“Field John (iOS)”, “Field Sam (web)”, “Field Paul (PHP)”]
let a = [20, 5, 8, 14, 9]
let b = a.filter{$0 > 10}
print(b) // [20, 14]
- Enumerations
In Swift, enumerations are more powerful and simple than they ever were in Objective-C. Now they can contain methods and be passed by value.
enum Location {
case Address(cityStr:String, streetStr:String)
case CoordinatesOfAddress(latitude:Float, longitude:Float)
func printOut() {
switch self {
case let .FullAddress(city, street):
print(“Address: ” + streetStr + “, ” + cityStr)
case let .CoordinatesOfAddress(latitude, longitude):
print(“Coordiantes Of Address: (\(latitude), \(longitude))”)
}
}
let location1 = Location.FullAddress(cityStr: “Nigdi”, streetStr: “Near Bhakti Shakti”)
let location2 = Location.CoordinatesOfAddress(latitude: 42.3586, longitude: -71.0590)
location1.printOut() // Address: Near Bhakti Shakti, Pune
location2.printOut() // Coordiantes: (18.6571, 73.7659)
- Functions
In Swift function syntax is flexible and simple. And also it allows defining default values for function parameters.
func stringCharactersCount(s:String) -> Int
{
return s.length
}
func printIntValue(someInt: Int = 5)
{ print(someInt) }
- Do Statement
In Swift, The do statement allows you to introduce a new scope.
In Do statement can contain one or more catch clauses.
do {
try expression
statements
} catch pattern exception1 {
statements
} catch pattern exception2 where condition {
statements
}