Swift: Class Prefix Needed?

Objective CNaming ConventionsSwift

Objective C Problem Overview


Should I give my Swift class names a three-letter prefix as recommended by Objective-C Conventions: Class Names Must Be Unique Across an Entire App?

Objective C Solutions


Solution 1 - Objective C

No, you do not need class prefixes in Swift, because classes are namespaced to the module in which they live.

If you need to disambiguate between (for example) an Array from Swift and an Array class/struct that you've declared in your app, you can do so by typing it as a Swift.Array or a MyProject.Array. That works with extensions as well:

extension Swift.Array {
    ...
}

extension MyProject.Array {
    ...
}

Solution 2 - Objective C

No, prefix is definitely not neeeded.

Suppose your app has MyApp name, and you need to declare your custom UICollectionViewController.

You don't need to prefix and subclass like this:

class MAUICollectionViewController: UICollectionViewController {}

Do it like this:

class UICollectionViewController {} //no error "invalid redeclaration o..."

Why?. Because what you've declared is declared in current module, which is your current target. And UICollectionViewController from UIKit is declared in UIKit module.

How to use it within current module?

var customController = UICollectionViewController() //your custom class
var uikitController = UIKit.UICollectionViewController() //class from UIKit

How to distinguish them from another module?

var customController = MyApp.UICollectionViewController() //your custom class
var uikitController = UIKit.UICollectionViewController() //class from UIKit

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionma11hew28View Question on Stackoverflow
Solution 1 - Objective CDave DeLongView Answer on Stackoverflow
Solution 2 - Objective CBartłomiej SemańczykView Answer on Stackoverflow