Some additional background in addition to the answers already provided: Objective-C Method
+ (id)buttonWithType:(UIButtonType)buttonType
returns id . It was a "traditional" way to declare a "factory" method so that it could also be used from subclasses. IN
UIButton *button = [UIButton buttonWithType: UIButtonTypeSystem];
because id can be converted to any Objective-C pointer.
Now the equivalent id type in Swift is AnyObject , and the above method maps to
class func buttonWithType(buttonType: UIButtonType) -> AnyObject!
Swift is much more strict and implicitly converts types, so the return value must be explicitly pointed to UIButton :
var button = UIButton.buttonWithType(UIButtonType.System) as UIButton
The "modern" approach for declaring factory methods is instancetype (see, for example, http://nshipster.com/instancetype/ or Would it be useful to start using instancetype instead of id? ). Simple example NSString method
+ (instancetype)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc
which is displayed in Swift on
class func stringWithCString(cString: CString, encoding enc: UInt) -> Self!
Self is the type of object the method is called on, so the return type
NSString.stringWithCString("foo", encoding: NSUTF8StringEncoding)
there is NSString! , and return type
NSMutableString.stringWithCString("bar", encoding: NSUTF8StringEncoding)
there is NSMutableString! . Swift does not require any casting. In the following examples, the Swift compiler “knows” that str is an NSString :
var str = NSString.stringWithCString("foo", encoding: NSUTF8StringEncoding) var cs = str.UTF8String
Foundation Foundation headers already use instancetype in many places, but not wherever possible (as in buttonWithType: . This may be improved in future releases of the SDK.