Are you looking to learn Swift by relating it to Objectve-C or learn Objective-C by relating it to Swift? Do you need a quick walkthrough of the syntax verbosity between the two languages?
Well you have landed on the right post. I myself learned Swift by relating all the concepts to Objective-C, which I was already well versed with. This post will also help you, if you are revamping an old Objective-C project with Swift or porting a Swift code base to Objective-C and need a quick lookup for the syntactical or logical errors.
There are definite possibilities for housing Swift and Objective-C code together but, this post is about the transition of syntax between the two languages.
If you started your journey with Objective-C and now moving on to Swift, it would be very easy for you to relate to the code flow. If you only have a Swift background, you might have to dig deep. This post will help you look through the differences, similarities and complexities of syntax between the two languages. You must be versed with either Objective-C or Swift in-order to grasp all the below topics.
Part – 1, of this post will include basic to intermediate topics covering Variables, Constants, Type Inference, Classes, Interfaces, Functions, Getters/Setters, Initializers, Loops and Arrays
Part – 2, will touch more complex things like Optionals, Wrapping/Unwrapping of variables, Type Casting, Closures/Blocks, Delegates, and Retain Cycle.
a.) Constants and Variables
- No need of * keyword to define pointer to objects.
- No need of @ prefix to specify a String Value.
- In Swift, “let” takes place of the “const” keyword.
- No need of semi-colon to mark the end of a statement, unless you are writing another one just after it (let color = “Blue” let anotherColor = “Red”, will throw an error)
- As the name suggests, you cannot change a constant (let and const)
- Notice how we don’t declare a datatype in Swift? We just use let and var, no NSString or NSNumber. Well that’s “Type Inference”. See the next point.
b.) Type inference
In Swift, If you want to just declare a variable and give it any value later, you have to use “Optionals”. This will be covered in Part 2 of this post.
let car: NSString? | let car: NSString!
For now, you can think of it as if the value is Optional, i.e it may or may not have any data. Only declaration, no assignment.
In Objective-C, we have Dynamic and Static Typing, which can be related to Type inference. Dynamic typing is when we use “id” to specify an object’s data type, which can store any value and no compile time check will be there.
id anArray = @[@“1”, @“2”, @“3”];
Static Typing ensures at compile time, that whatever data type you are using while creating an object, it should store that exact data. If not, you’ll see compiler warnings.
NSString *aString = [NSNumber numberWithInt:1];
Error: Incompatible pointer types, Initializing NSString with NSNumber
Unlike Objective-C, sending multiple parameters to a function is very easy in Swift.
- “func” keyword is necessary in Swift to specify the function. Objective-C uses “-” instead.
- Whatever a function can return should be specified with “->” keyword in Swift and inside circular braces in Objective-C (- (int) addTwoNumbers, here this function would return an integer).
- “_” can be specified as an parameter label (see “subtractTwoNumbers” function) which will ensure that you can call the method without any parameter names in Swift.
d.) NSLog & print
- %@ and %d are format specifiers in Objective C. %@ can be used for any object, %d and %f are used for integer and float primitives.
- Swift provides easy way to concatenate strings using the “+” operator. In place of a format specifier, you can wrap your variables in “\(myVariable)”, to print it or concatenate it, irrespective of the data type.
e.) Image bindings
While Objective-C keeps it simple with UIImage Class to handle image operations, here’s a cool thing about Swift; while assigning an Image to a UIImage Object, you can directly type the name of image and AutoHelp will show that image itself. There’s more, when you tap on that image, it will show you all the other images in your project bundle and you can select from there also.
f.) Class & Interface
Objective-C provides two files for every Class/Interface, with “.h” and “.m” extensions. Swift only provides one “.swift”.
Purpose of two files in Objective-C is to keep declaration and definition separately. “.h” is used for declaration only, while “.m” is used for implementation. Also, you always import “.h” so that all the implementation specific stuff is not imported, providing sanity and giving some good safety against circular imports.
In order to initialize variables of your class, we use initializer functions.
To initialize your variables in a class you must call the init function.
In Objective-C we have to call “alloc” first, which allocates the memory for your object and returns a pointer and “init” sets up and returns the object. You can override init method to setup your object.
In Swift, you can simply use circular braces and class name to do the same as above.
h.) Getters & Setters
Objective-C only allows overriding of Getter and Setters for variables declared using @property attribute. Swift has no such conditions.
- Objective C requires @synthesize call to work with both getters and setters. If you only have to use one at a time, @synthesize call can be eliminated, Objective-C will provide one (_aNumber) by itself.
- In Swift, there is no @synthesize call. The setter doesn’t take an explicit parameter for setting the value unlike Objective-C. Instead, you can use the implicit “newValue” parameter, which will provide the same functionality.
- In Swift, If you override a setter, you must provide a getter. Objective-C has no such restrictions.
Please refer the numbered list with above image:
- This is how you define an immutable array. Immutable can not be changed that’s why its Swift equivalent uses “let”, which also signifies a constant.
- Arrays can be accessed via position number in both the languages.
- Arrays created via NSMutableArray and var are mutable and can be modified later on.
- By default if you call addObject or append or +=, object will be added at the last index. If you want to insert in between, then insertObject and insert can be used respectively in Objective-C and Swift.
- In order to create an array with multiple data types you have to specify “[Any]” attribute in Swift, otherwise you’ll get an error “Heterogeneous collection literal could only be inferred to ‘[Any]'; add explicit type annotation if this is intentional”. For Objective-C there is no such restriction.
- Circular braces are stripped in Swift for all the conditions in loops. Although you can use them, if you prefer to do so.
- Objective C follows the same C type format, i.e, initial value, condition and increment style for “for” loop. Swift makes it easy with “in” and “…”, three dot keyword. Numbers written before and after the three dots are always inclusive of the loop count.
- For Swift only background people, @1 in Objective-C means defining a NSNumber Object with Integer value in it.