Swift Xcode 6.1 破坏了我的代码 |操作数错误

标签 swift compiler-errors operand cgfloat

所以每当我有这个:

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创建失败,应用程序将崩溃。
  • 使用可选绑定(bind):
    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/

    相关文章:

    compiler-errors - dev86编译错误

    mysql - 在 IN 查询(​​子查询)上选择另一列

    mysql - 操作数应包含 1 列 数据库错误

    python - 为什么返回 Nonetype?

    ios - 获取firebase服务器时间云函数

    ios - Swift - 自定义 MKAnnotationView,设置标签标题

    swift - 漏洞 : hit-testing with sibling nodes and the userInteractionEnabled property in Sprite Kit

    ios - 无法创建可重用 View 的实例

    reactjs - 对 child 使用 “React.ReactNode”类型时出错。我应该使用哪种类型?

    java - 从: javac error来源构建RStudio