Swift vs Objective-C
Open an older iPhone project and you may find files ending in .h and .m, full of square brackets. That is Objective-C, the language Apple apps were written in before Swift. You will still meet it, so it helps to recognise it and know why Swift took over.
The rule
Objective-C is C plus messages; Swift is safety by default.
Objective-C dates from the 1980s. It is the C language with a layer on top for sending messages to objects, written in square brackets. Each class usually lives in two files: a header (.h) that declares it and an implementation (.m) that defines it.
NSString *name = @"Read";
[tracker markDone:name];Swift does the same job with one file per type, no header, and lighter syntax:
let name = "Read"
tracker.markDone(name)The deeper difference is what happens when something is missing. In Objective-C, sending a message to nil (nothing) quietly does nothing and returns zero or nil, so a bug can hide for a long time. In Swift, a value that might be missing has its own type, an optional, and you must handle it before use.
The two are not enemies. They can live in the same project and call each other. Many apps are a mix, and older Apple frameworks like UIKit were written in Objective-C yet are used from Swift every day.
The shortcut
Spot the language by three tells: square brackets, @"..." strings, and .h/.m files mean Objective-C. Dots for calls, plain "..." strings and .swift files mean Swift. Then remember the one behaviour that matters most: Objective-C forgives nil silently, Swift makes you face it.
Look at the file name
HabitStore.mends in.m. This is Objective-C.
The trap is assuming you must rewrite old Objective-C before adding Swift. You do not; add new Swift files beside the old ones and move over gradually.
Drills
Answer fast — trust the rule.
Which line is Objective-C?
In Objective-C, what happens when you send a message to nil?
Can a Swift file and an Objective-C file be part of the same app?
Where does an Objective-C class usually keep its public declarations?
Remember
- Objective-C is C plus messages; Swift is safety by default.
- Tells: square brackets,
@"..."and.h/.mmean Objective-C. - The two mix in one app, so there is no need to rewrite everything at once.
