Constants in Objective-C

Recently I was working on a legacy project written in Objective-C, which reminded me of the early days when working on Objective-C projects.

In the code I saw few things like the following which defines a constant:

#define car_price 300

#define creates a macro which simply do the replacement for the compiler. In the above code, compiler doesn't know the type of the card_height. It must be converted to a float value when using. So it is not type-safe.

Instead of using a macro to define a constant, it is a better way to use const to define a constant as it is type-safe and easier to debug.

static float const kCarPrice = 300.0f;

Also we can use const to define other types of constants too.

static NSString* const kCarModel = @"Lexus IS 200T"; 
static in const KCarType = 1;

Noticed that const can only used before immutable variables. So the following two statements are the same, both kCarModel1 and kCarModel2 are immutable, even if they have the type of NSMutableString.

static NSString* const kCarModel1 = @"Lexus IS 200T"; 
static NSMutableString* const kCarModel2 = @"Lexus IS 200T";

Originally published at https://needone.app on December 12, 2020.

--

--

--

needone.app

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Django Password Reset Email in PythonAnywhere

Ujo Public Alpha Technical Stack

Truecaser

ROBURNA ENGAGED INTO A PARTNERSHIP WITH METABOTS

Tales from the Serverless landscape

How to resolve the Django-Postman CSRF Token error?

Android fundamentals 05.1: Drawables, styles, and themes

Neovim for Beginners — Debugging using DAP

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Needone App

Needone App

needone.app

More from Medium

Why can Double() store a larger # than Int() ?

How to Create Localizable and Use for Swift

The importance of documentation

Add a new file using: File, New, File, Documentation Catalog

How to use async/await in synchronous Swift code with tasks