【问题标题】:Swift: Class Prefix Needed?Swift:需要类前缀?
【发布时间】:2014-06-13 23:00:01
【问题描述】:

我是否应该按照Objective-C Conventions: Class Names Must Be Unique Across an Entire App 的建议为我的 Swift 类名添加三个字母的前缀?

【问题讨论】:

  • 现在,Apple 甚至在 Swift 中使用 NSNotificationCenter 等类时去掉了 NS 前缀。但是,他们仍然保留NSObject 的前缀,这就是为什么我们都在这里玩得很开心。

标签: objective-c naming-conventions swift


【解决方案1】:

不,you do not need class prefixes in Swift,因为类被命名为它们所在的模块。

如果您需要区分(例如)来自 Swift 的 Array 和您在应用中声明的 Array 类/结构,您可以将其键入为 Swift.ArrayMyProject.Array。这也适用于扩展:

extension Swift.Array {
    ...
}

extension MyProject.Array {
    ...
}

【讨论】:

  • 如果您导入到目标 c 中,这是否会结转?
  • @Jeef This Stackoverflow answer 似乎表明将类导入Objective-C时可能会发生命名冲突。
  • 由于您在导出时选择带有@objc 标签的类名,我认为您应该两者都做,所以在Swift 中SimpleAlert 变为DRSimpleAlert
【解决方案2】:

不,绝对不需要前缀。

假设您的应用具有MyApp 名称,并且您需要声明您的自定义UICollectionViewController

不需要像这样添加前缀和子类:

class MAUICollectionViewController: UICollectionViewController {}

这样做:

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

为什么?。因为您声明的内容是在当前模块中声明的,这是您的当前目标。而来自UIKitUICollectionViewControllerUIKit 模块中声明。

如何在当前模块中使用它?

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

如何将它们与其他模块区分开来?

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

【讨论】:

  • 这如何与 Objective-C 一起工作?例如,如果要在 ObjC 中创建此 Swift 子类的实例,您将调用:[UIViewController alloc] init]。
猜你喜欢
  • 2011-08-05
  • 2011-09-22
  • 2018-12-24
  • 2012-12-10
  • 2012-01-09
  • 2013-05-14
  • 2011-07-11
  • 2010-12-14
  • 2018-03-25
相关资源
最近更新 更多