除了已經給出答案,一些額外的背景: Objective-C的方法
+ (id)buttonWithType:(UIButtonType)buttonType
回報id
。這是以「傳統」方式申報「工廠方法」的方式,因爲它也可以從子類中使用 。沒有類型在
UIButton *button = [UIButton buttonWithType: UIButtonTypeSystem];
投必要的,因爲id
可被轉化爲任何Objective-C的指針。
現在夫特等效類型id
是AnyObject
,並且上述方法被映射到
class func buttonWithType(buttonType: UIButtonType) -> AnyObject!
夫特得多嚴格和不不隱性轉換的類型,因此返回值必須是轉換爲UIButton
明確:
var button = UIButton.buttonWithType(UIButtonType.System) as UIButton
「現代」 Appro公司ach宣佈工廠方法是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
其在夫特映射到
class func stringWithCString(cString: CString, encoding enc: UInt) -> Self!
Self
是在其上調用方法的對象的類型,從而使 的
返回類型
NSString.stringWithCString("foo", encoding: NSUTF8StringEncoding)
是NSString!
和返回類型
NSMutableString.stringWithCString("bar", encoding: NSUTF8StringEncoding)
是NSMutableString!
。 Swift中不需要類型轉換。在下面的例子 ,雨燕編譯器「知道」 str
是NSString
:
var str = NSString.stringWithCString("foo", encoding: NSUTF8StringEncoding)
var cs = str.UTF8String
Foundation框架頭已經在很多地方使用instancetype
,但不 尚未無處不在可能情況下(如在buttonWithType:
)。這可能會在 SDK的未來版本中得到改進。
許多** **你的問題是,我也想問*好奇*基本問題(但我猜你在學習曲線上比我早2年)。通常你不會找到這樣的問題的答案,除非在SO上被問到。 – Honey