除了已经给出的答案之外的一些其他背景:
Objective-C方法
+ (id)buttonWithType:(UIButtonType)buttonType
返回id。这是声明“工厂方法”的“传统”方式
也可以从子类中使用。在
中不需要类型转换
UIButton *button = [UIButton buttonWithType: UIButtonTypeSystem];
因为id 可以转换为任何Objective-C 指针。
现在Swift中id的等价类型是AnyObject,上面的方法映射到
class func buttonWithType(buttonType: UIButtonType) -> AnyObject!
Swift 更加严格,并且 not 隐式转换类型,因此返回值必须显式转换为 UIButton:
var button = UIButton.buttonWithType(UIButtonType.System) as UIButton
声明工厂方法的“现代”方法是instancetype(参见例如http://nshipster.com/instancetype/ 或Would it be beneficial to begin using instancetype instead of id?)。一个简单的例子是
NSString 方法
+ (instancetype)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc
在 Swift 中映射到
class func stringWithCString(cString: CString, encoding enc: UInt) -> Self!
Self 是调用方法的对象的类型,因此
的返回类型
NSString.stringWithCString("foo", encoding: NSUTF8StringEncoding)
是NSString!,返回类型是
NSMutableString.stringWithCString("bar", encoding: NSUTF8StringEncoding)
是NSMutableString!。 在 Swift 中不需要类型转换。在下面的
例如,Swift 编译器“知道”str 是 NSString:
var str = NSString.stringWithCString("foo", encoding: NSUTF8StringEncoding)
var cs = str.UTF8String
Foundation 框架头文件已经在很多地方使用了instancetype,但不是
但在任何可能的地方(如buttonWithType:)。这可能会在
SDK 的未来版本。