The Conciseness of Swift

Alexey Kuznetsov
Swift Programming
Published in
1 min readAug 8, 2016

After writing in Swift for about a year almost exclusively, I sometimes forget how concise it is compared to Objective-C. Especially when you use similar safety features like nullability and designated initializer declarations.

Take a look at this example of an app receipt validation. It’s a simple decorator implementing one of the steps in the validation process and its goal is to verify the receipt’s attributes.

ReceiptAttributesValidation is an immutable object that doesn’t use nil. It doesn’t have accessors to protect its internals and avoid the Law of Demeter violations. It explicitly declares its designated initializer and prevents an accidental initialization with an initializer inherited from the parent.

The object’s API doesn’t allow an incorrect usage. The client can only create an object using a single (in this case) initializer and tell the object to do work.

And here’s the same class implemented in Swift. Note also how the possibility to use a where clause in optional bindings allowed us to remove one method (assuming we wanted to keep methods small).

And what do you think about Swift’s brevity? Do you miss Objective-C’s verboseness in your code?

Other Articles

--

--