【问题标题】:Swift Xcode 6.1 broke my code | Operand errorSwift Xcode 6.1 破坏了我的代码 |操作数错误
【发布时间】:2014-11-03 15:31:41
【问题描述】:

所以每当我有这个:

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;

【问题讨论】:

  • UIImage 有一个sizeUIImage? 没有。
  • 仍然不起作用:UIImage.size.height。得到同样的错误,所以这不是问题
  • 您能否解释一下这一点:“使用可选链解开图像的可选并使用 UIImage 的 frame 属性。”不太明白。
  • 你能在我的代码中显示它吗?如果你愿意,你可以编辑它

标签: swift compiler-errors operand cgfloat


【解决方案1】:

在这一行:

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 为nil,image.size.height 的计算结果为nil

为了避免这种情况,您有两种选择:

  1. 通过使用强制展开使image 成为非可选

    let image = UIImage(named: imageNamed)!
    

    但我不建议使用它,因为如果 UIImage 创建失败,应用程序将崩溃。

  2. 使用可选绑定:

    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 语句中的代码将被跳过并且不会发生运行时错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    相关资源
    最近更新 更多