我正在看这个Swift教程,下面是这样的一句话:
var button:UIButton = UIButton.buttonWithType(UIButtonType.System) as UIButton两个问题:
as UIButton结尾?行不够清楚吗?用户想要创建一个系统类型的按钮吗?这似乎是多余的。var按钮= UIButton.buttonWithType(UIButtonType.System)
我的意思是,如果等号后面的部分是初始化系统类型的按钮,那么编译器不足以推断button是UIButton吗?我的意思是,苹果公司说编译器在推断类型方面很聪明。
发布于 2014-07-01 19:43:47
你需要保持as UIButton下降。buttonWithType()返回的是AnyObject!,而不是UIButton,所以下行是必要的。除此之外,您不需要使用: UIButton显式地键入变量。由于将buttonWithType()的返回类型向下转换为UIButton,因此变量类型将被推断为UIButton。这是您应该使用的:
var button = UIButton.buttonWithType(UIButtonType.System) as UIButton发布于 2014-07-01 19:45:12
如果您单击buttonWithType,您将看到它在迅速地声明为
class func buttonWithType(buttonType: UIButtonType) -> AnyObject!因为它返回的类型是AnyObject!您需要将其类型转换回UIButton。
发布于 2016-03-02 09:24:51
Swift 2.1现在
var button = UIButton(type: .System)所以不需要用.buttonWithType
https://stackoverflow.com/questions/24517713
复制相似问题