所以每当我有这个:
let result = SKScrollingNode(color: UIColor.clearColor(), size:CGSizeMake(CGFloat(containerWidth), image.size.height));
我收到 image.size.height 的编译错误,告诉我“'UIImage?'没有名为“size”的成员,尽管它有
知道这意味着什么以及如何解决吗?
谢谢!
整个代码片段:
class func scrollingNode(imageNamed: String, containerWidth: CGFloat) -> SKScrollingNode {
let image = UIImage(named: imageNamed);
let result = SKScrollingNode(color: UIColor.clearColor(), size: CGSizeMake(CGFloat(containerWidth), image.size.height));
result.scrollingSpeed = 1.0;
var total:CGFloat = 0.0;
while(total < CGFloat(containerWidth) + image.size.width!) {
let child = SKSpriteNode(imageNamed: imageNamed);
child.anchorPoint = CGPointZero;
child.position = CGPointMake(total, 0);
result.addChild(child);
total+=child.size.width;
}
return result;
最佳答案
在这一行:
let image = UIImage(named: imageNamed)
image
是可选的,UIImage?
.这一行的错误:
let result = SKScrollingNode(color: UIColor.clearColor(), size: CGSizeMake(CGFloat(containerWidth), image.size.height));
可以缩小到这段代码:
CGSizeMake(CGFloat(containerWidth), image.size.height)
CGSizeMake
需要 2 CGFloat
参数,但第二个是可选的,因为 image
是可选的:image
不为零,image.size.height
计算为 CGFloat image
为零,image.size.height
评估为零 为了避免这种情况,您有两种选择:
image
使用强制展开的非可选let image = UIImage(named: imageNamed)!
但我不推荐使用它,因为如果
UIImage
创建失败,应用程序将崩溃。 let image = UIImage(named: imageNamed);
if let image = image {
let result = SKScrollingNode(color: UIColor.clearColor(), size: CGSizeMake(CGFloat(containerWidth), image.size.height));
// ... rest of the code here
}
这是解开可选项的更好方法,因为如果它为 nil,
if
中的代码语句将被跳过并且不会发生运行时错误。 关于Swift Xcode 6.1 破坏了我的代码 |操作数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26717452/