Deepak Sharma
Deepak Sharma

Reputation: 6537

Avoiding type name conflicts in Swift

I am writing a static library in Swift that will be reused in multiple projects. The problem is class and struct names I am using are common and can easily conflict with other libraries/frameworks. I don't see any obvious way to create my own namespace in Swift. What's the best way to avoid name collision between classes in multiple libraries/frameworks?

Upvotes: 4

Views: 4189

Answers (2)

Duncan C
Duncan C

Reputation: 131471

As others have said, if there is a conflict, you can always fully qualify the symbol name with the module name (See Cong's answer.)

Apple's suggested way to handle this in the days of Objective-C was to use your intials or your company's initials as a prefix for your symbol names. I'm not a big fan of that since it creates ugly names that obscure the underlying meaning.

Using an abbreviated version of the module name/framework name is a little better, and what Apple tends to do, e.g. UIKit views are UIViews, and AFNetworking's connection object might be an AFNConnection.

Others are arguing strongly in the comments that this is no longer needed and no longer recommended. (Like I said, I've never liked it anyway.)

Upvotes: 3

congnd
congnd

Reputation: 1284

You don't to have to avoid. Just use the name you like. Then when you want to access to your class/struct/protocol..., just use your module name as a namespace.

Example:

import MyModule

let a: MyModule.Result // the Result type defined inside the `MyModule`
let b: Result // Swift's Result type

Upvotes: 10

Related Questions