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

后端 未结 7 666
面向向阳花
面向向阳花 2021-01-29 20:43

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 exten

7条回答
  •  被撕碎了的回忆
    2021-01-29 21:20

    Rather than adding my comments all over the place, I'm surfacing them all here in one answer.

    Personally, I take a hybrid approach that gives both good usability and clarity, while also not cluttering up the API surface area for the object that I'm extending.

    For instance, anything that makes sense to be available to any string would go in StringExtensions.swift such as trimRight() and removeBlankLines().

    However, if I had an extension function such as formatAsAccountNumber() it would not go in that file because 'Account Number' is not something that would naturally apply to any/all strings and only makes sense in the context of accounts. In that case, I would create a file called Strings+AccountFormatting.swift or maybe even Strings+CustomFormatting.swift with a formatAsAccountNumber() function if there are several types/ways to actually format it.

    Actually, in that last example, I actively dissuade my team from using extensions like that in the first place, and would instead encourage something like AccountNumberFormatter.format(String) instead as that doesn't touch the String API surface area at all, as it shouldn't. The exception would be if you defined that extension in the same file where it's used, but then it wouldn't have it's own filename anyway.

提交回复
热议问题