Swift: Forbid use of original class name after creating a typealias

136 Views Asked by At

Is it possible in Swift to forbid the use of the original class name in my program after the creation of a typealias?

Hi,

To avoid inconsistent use of class name in my program I would like to force the systematic use of the alias name instead of the original class name in my program. Is it possible to do that?

I am using an external library, in which there is a class that does not exactly what it is supposed to do: the name of that class in the library seems incorrect to me. How can I handle this?

eg. a class Dog that has a function meows instead of barks, and I want to rename it Cat and then call exclusively Cat in my program.

2

There are 2 best solutions below

0
Rob Napier On

Applying a consistent style like this is the job of a linter, not the compiler. For swiftlint, you'd write a rule something along these lines. (This is untested, but based on the pirates_beat_ninjas example from the documentation.)

custom_rules:
  cats_not_dogs:
    included: 
      - ".*\\.swift" 
    name: "Use Cat rather than Dog"
    regex: "Dog"
    match_kinds:
      - identifier
    message: "Use Cat rather than Dog."
    severity: error
0
Caleb On

I am using an external library, in which there is a class that does not exactly what it is supposed to do: the name of that class in the library seems incorrect to me. How can I handle this?

One option is to create your own library that wraps the offending one and only exposes your names.

Since your question is tagged I'll assume that we're actually talking about Swift packages here. Let's say that the package you're using is called Canine, and that it includes a class Dog, which you would prefer to call Cat. You can create a new package, say, Feline, that has a file Feline.swift like:

import Canine

public typealias Cat = Dog

Now you can add the Feline package to your app, and import Feline to whichever source files need it. The Canine package will be added to the app as a dependency, but as long as you don't add import Canine to your source files, the compiler will prevent you from using Dog directly.

This seems like a lot of trouble to go to just because you don't like the name of a class. Even so, I can imagine some reasons why it might be worth the effort, e.g.:

  • Many of the names in Canine are poorly chosen;

  • Your company was recently acquired, and you want to rename the types in your library to include the new name or hide the old one;

  • You have several different libraries that you want to build your app against without having to change the names in the source code. (Protocols might be a better option in this case.)