作为UIButton在swift中的UIButton?

问题描述:

我看着这斯威夫特教程并没有这一行:作为UIButton在swift中的UIButton?

var button:UIButton = UIButton.buttonWithType(UIButtonType.System) as UIButton 

两个问题:

  1. 这是为什么符合as UIButton结束?这行不够清楚,用户想要创建一个系统类型的按钮?这似乎是多余的。
  2. 是否有必要在该行的第一部分声明UIButton类型?或者换句话说,是不够的,声明它像

VAR键= UIButton.buttonWithType(UIButtonType.System)

我的意思是,如果等号后的部分被初始化系统类型的按钮不够编译器推断buttonUIButton?我的意思是,苹果说编译器聪明地推断类型。

+0

许多** **你的问题是,我也想问*好奇*基本问题(但我猜你在学习曲线上比我早2年)。通常你不会找到这样的问题的答案,除非在SO上被问到。 – Honey

你需要保持as UIButton向下。 buttonWithType() return AnyObject!,而不是UIButton,所以downcast是必要的。除此之外,您不需要使用: UIButton明确输入变量。由于buttonWithType()的返回类型向下转换为UIButton,因此变量类型将被推断为UIButton。这是你应该使用什么:

var button = UIButton.buttonWithType(UIButtonType.System) as UIButton 
+11

而其根本原因似乎是Objective-C方法'buttonWithType:'被声明为返回'id'而不是'instancetype'。 –

+2

来自Martin的完美anser和完美评论!现在我看到,AnyObject! = id!谢谢!!! – SpaceDog

+0

从Swift 1.2开始,你需要使用'as!'强制执行一个downcast –

如果CMD点击buttonWithType你会看到,在迅速的声明为

class func buttonWithType(buttonType: UIButtonType) -> AnyObject! 

因为它返回的类型是AnyObject!你需要输入回到UIButton。

+3

它实际上是一个可选的,它可以是nil – Sulthan

+0

你是对的,我在前面想,会编辑我的文章,感谢你的支持。 –

除了已经给出答案,一些额外的背景: Objective-C的方法

+ (id)buttonWithType:(UIButtonType)buttonType 

回报id。这是以“传统”方式申报“工厂方法”的方式,因为它也可以从子类中使用 。没有类型在

UIButton *button = [UIButton buttonWithType: UIButtonTypeSystem]; 

投必要的,因为id可被转化为任何Objective-C的指针。

现在夫特等效类型idAnyObject,并且上述方法被映射到

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中不需要类型转换。在下面的例子 ,雨燕编译器“知道” strNSString

var str = NSString.stringWithCString("foo", encoding: NSUTF8StringEncoding) 
var cs = str.UTF8String 

Foundation框架头已经在很多地方使用instancetype,但不 尚未无处不在可能情况下(如在buttonWithType:)。这可能会在 SDK的未来版本中得到改进。

+0

这些按钮是怎么样的* class *方法?或者,UIButton的**实例**等于UIButton的工厂方法/类方法之一? – Honey

+0

@Honey:'UIButton.buttonWithType(...)'是一个类方法(或者更好:在Swift 1中是类方法)。 –

+0

我得到的那部分,但不要混淆,因为在如何变异,即是一个实例是从一个类的方法派生 – Honey

雨燕2.1是现在

var button = UIButton(type: .System) 

所以没有必要用.buttonWithType向下转型