作为UIButton在swift中的UIButton?
我看着这斯威夫特教程并没有这一行:作为UIButton在swift中的UIButton?
var button:UIButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
两个问题:
- 这是为什么符合
as UIButton
结束?这行不够清楚,用户想要创建一个系统类型的按钮?这似乎是多余的。 - 是否有必要在该行的第一部分声明UIButton类型?或者换句话说,是不够的,声明它像
VAR键= UIButton.buttonWithType(UIButtonType.System)
我的意思是,如果等号后的部分被初始化系统类型的按钮不够编译器推断button
是UIButton
?我的意思是,苹果说编译器聪明地推断类型。
你需要保持as UIButton
向下。 buttonWithType()
return AnyObject!
,而不是UIButton
,所以downcast是必要的。除此之外,您不需要使用: UIButton
明确输入变量。由于buttonWithType()
的返回类型向下转换为UIButton,因此变量类型将被推断为UIButton
。这是你应该使用什么:
var button = UIButton.buttonWithType(UIButtonType.System) as UIButton
而其根本原因似乎是Objective-C方法'buttonWithType:'被声明为返回'id'而不是'instancetype'。 –
来自Martin的完美anser和完美评论!现在我看到,AnyObject! = id!谢谢!!! – SpaceDog
从Swift 1.2开始,你需要使用'as!'强制执行一个downcast –
如果CMD点击buttonWithType你会看到,在迅速的声明为
class func buttonWithType(buttonType: UIButtonType) -> AnyObject!
因为它返回的类型是AnyObject!你需要输入回到UIButton。
它实际上是一个可选的,它可以是nil – Sulthan
你是对的,我在前面想,会编辑我的文章,感谢你的支持。 –
除了已经给出答案,一些额外的背景: 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.1是现在
var button = UIButton(type: .System)
所以没有必要用.buttonWithType向下转型
许多** **你的问题是,我也想问*好奇*基本问题(但我猜你在学习曲线上比我早2年)。通常你不会找到这样的问题的答案,除非在SO上被问到。 – Honey