24 Utilities (extension) to make the Code clearer!

Tram Ho

In my opinion, one of the best features of both Swift and Objective-C is extensions. They allow you to add new methods to any class, and the entire project will be able to call them without inheriting and overloading.

As a mobile developer, I work with both iOS and Android, and I often see Android functions and methods shorter, cleaner, and easier to understand in Swift. Along with some new methods (extensions), we get a brief, clean, and easy to maintain code snippet in Swift.

I’ll be using Swift, but all of these extensions can be converted to Objective-C or used with Objective-C directly without conversion.

String.trim () and Swift.trimmed

In 99% of cases when I cut a String in Swift, I want to remove spaces and other similar symbols (e.g. new lines and tabs).

This simple extension does the trick:

Use:

Int.toDouble () and Double.toInt ()

These methods can be helpful if you work with options. If you have no Int option, you can convert it with Double (a), where “a” is an integer variable. But if “a” is optional, you can’t do it.

Let’s add extensions to Int and Double:

Use:

String.toDate (…) and Date.toString (…)

Retrieving Datet from String and formatting Date to display or send to API is common practice. The standard conversion method requires three lines of code. Let’s see how to make it shorter:

Use:

Int.centsToDollars ()

Some payment APIs (e.g. Stripe) prefer to use currency (cents) to process payments. It allows to avoid inaccuracies of Float and Double. At the same time, it would be more comfortable to use these types to display the value.

This extension does this conversion:

Use:

String.asCoferences ()

The coordinates of a place on Earth have at least two numbers – latitude and longitude. Another one is the height, but that only makes sense in 3D, which isn’t very common in software development.

From the API we get two separate fields, or one with comma separated values. This extension allows to perform conversion of such strings into CLLocationCoordinate2D.

Use:

String.asURL ()

iOS and macOS use type URLs to handle the links. It’s more flexible, allowing for different types of URLs to be grabbed and handled. At the same time, we usually import it or get it from the String API. It’s pretty easy to convert one to another, but this extension allows us to handle these options or conversion strings:

Use:

UIDevice.vibrate ()

IPhone vibrations can be a great effect for button presses and other feedback from the device. For iPhone vibrations, there is a special sound that is handled by AudioToolbox framework.

For the AudioToolbox with all UIViewControllers vibrating is annoying and logically, vibration is a function of the device (it is not coming from the speaker but from the device itself) rather than playing the sound.

This extension allows to simplify it to one line:

Use:

String.width (…) and String.height (…)

iOS can UILabelt automatically compute the size using the constraints provided, but sometimes it’s important that you set the size yourself.

This extension allows us to calculate String width and height using UIFont:

Use:

String.containsOnlyDigits

The extension below is useful when you need to limit user input or validate data from the API. It checks if the String has only digits:

Use:

String.isAlphanumeric

Like the previous extension, this extension checks the contents of the String. It returns true if the string is not empty and contains only alphanumeric characters. A reverse version of this extension can be helpful for confirming that the password contains non-alphanumeric characters.

Use:

Sign up for the chain

Swift 5 has a way to register String. Computing the indices and offsets is annoying if you want to get the characters 5 through 10. This extension allows simple Int to be used for this purpose:

Use:

UIImage.squared

When you ask users to take their photo or choose an existing photo as their profile photo, it will be difficult for them to provide a square photo. At the same time, most UIs use either square or circle. This extension cuts the UIImage offered, turning it into a perfect square:

Use:

UIImage.resize (…)

Before uploading images to the server, you must ensure that the image is small enough. iPhone and iPad have very good cameras and photos from their gallery are of unlimited size. To make sure UIImage that size is not larger than a certain size, for example: 512 pixels or 1024 pixels use this extension:

Use:

The last two extensions can be chained:

Int.toString ()

One of Java’s most useful features is the toString () method. It is a method of all classes and types. Swift allows to do something similar using the inference string: “(someVar)”. But there is one difference – your variable is optional. Swift will add the word optional to the output. Java will only crash, but Kotlin will handle the options nicely: someVar? .ToString () will return an Option String, which is null (nil) if someVarl and null (nil) or String contain a value. .

Unfortunately, Swift doesn’t allow Any extension, so add the least toString () method to Int:

Use:

Double.toString ()

As in the previous example, converting Double to String can be very helpful. But in this case, we will limit the output to two fractional digits. I can’t say this extension will be useful for every situation, but for most use cases it should work fine:

Use:

Double.toPrice ()

Creating Strings for a price is just another way to format Doubles. This algorithm is uncommon, it depends on the regional settings. But you can use it as a general idea and make adjustments to your application:

Use:

String.asDict

JSON is a popular format for exchanging or storing structured data. Most APIs prefer to use JSON. JSON is a JavaScript structure. Swift has the same data type – dictionary.

Converting one into a trick is quite simple:

Use:

String.asArray

This extension is similar to the previous one, but it converts the JSON array into a Swift array:

Use:

String.asAttributedString

Sometimes we need some kind of background-independent simple text. A fairly common way is to use plain HTML for this purpose.

UILabel can display text with bold (<strong>) sections, underlined text, larger and smaller paragraphs, etc.You just need to convert the HTML to NSAttributedString and assign it to UILabel.attributedText.

This extension will help you to do the first task:

Use:

Bundle.appVersion

The last extension in this collection allows the application version to be obtained from the Info.plist file. It may be useful for:

  • Submit the version of the application to the API.
  • Check for available updates.
  • Display the application version on the device screen.
  • Include the application version in support email. The extension below allows you to load the application version (or nil if it isn’t available) in one line of code:

Use:

Conclusion

I hope these extensions have helped you make your code shorter and clearer. Please modify them to meet your requirements and include them in your projects.

Link article references: https://medium.com/better-programming/24-swift-extensions-for-cleaner-code-41e250c9c4c3?fbclid=IwAR1KzYlRt0MzLbF-QlFQGyy-Fsiga1DCnKsMQuGoCvf2gnaS530nMA1Y7e

Have a good time and see you next time!

Share the news now

Source : Viblo