What's the best practice for naming Swift files that add extensions to existing objects?


There is no single "best" practice for naming Swift files that add extensions to existing objects, but here are some commonly used conventions −

Object Prefix Followed by Functionality

  • String+Utilities.swift − adds utility functions to the String class

  • Array+Sorting.swift − adds sorting functions to the Array class

  • UIColor+Extensions.swift − adds color-related functions to the UIColor class

Functionality Prefix Followed by Object

  • CustomView+Animation.swift − adds animation functionality to a custom view class called CustomView

  • JSONEncoder+CustomEncoding.swift − adds custom encoding and decoding functionality to the JSONEncoder class

  • UICollectionViewLayout+Extensions.swift − adds layout-related functions to the UICollectionViewLayout class

Descriptive Naming

  • Date+ISO8601String.swift − adds functions to the Date class for working with ISO 8601 formatted strings

  • UIImage+Manipulation.swift − adds image manipulation functions to the UIImage class

  • URLSession+Retry.swift − adds functionality to retry failed network requests using the URLSession class

Here are some additional points to consider when naming Swift files that add extensions to existing objects

  • Be precise and descriptive − Give the file a name that correctly represents its goal. A descriptive name helps other writers comprehend what the file does without having to read the code.

  • Maintain uniform labeling conventions − Choose a pattern and use it consistently throughout your software. This makes it simpler for coders to find relevant files and ensures that your software is well-organized and understandable.

  • Avoid using acronyms − While they may appear to be handy, abbreviations can be perplexing and difficult to comprehend. Use complete words that correctly explain the new functionality.

  • Choose a short and simple name − Your file name should be straightforward to write, read, and recall. Avoid names that are too lengthy or challenging to say.

  • Separate the item and the extension with a + sign − The plus symbol distinguishes the object name from the extended name when naming files that add extensions to current objects. String+Utilities.swift, for example.

  • To prevent naming conflicts, choose an alternative name if you're adding an extension to an object that already has an extension with the same name.

Conclusion

By following the good and proper naming convention, you can organize your files properly. It will help you easy to handle and modifications in the extension. When we work on large projects that contain many extension files, naming convention does matter a lot.

Updated on: 04-May-2023

541 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements