AlBlue AlBlue - 2 years ago 961
Swift Question

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

It's possible to add extensions to existing Swift object types using extensions, as described in the language specification.

As a result, it's possible to create extensions such as:

extension String {
var utf8data:NSData {
return self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

However, what's the best naming practice for Swift source files containing such extensions?

In the past, the convention was to use
for the Objective-C
type as discussed in the Objective-C guide. But the Swift example doesn't have a category name, and calling it
doesn't seem appropriate.

So the question is: given the above
extension, what should the swift source file be called?

Answer Source

Most examples I have seen mimic the Objective-C approach. The example extension above would be:


The advantages are that the naming convention makes it easy to understand that it is an extension, and which Class is being extended.

The problem with using Extensions.swift or even StringExtensions.swift is that it's not possible to infer the purpose of the file by its name without looking at its contents.

Using xxxable.swift approach as used by Java works okay for protocols or extensions that only define methods. But again, the example above defines an attribute so that UTF8Dataable.swift doesn't make much grammatical sense.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download