可选类型和UIDynamicAnimator的问题

时间:2014-11-13 22:40:02

标签: cocoa swift

我正在使用Cocoa进行O' Reilly的Swift开发,并收到以下错误:

Bound value in a conditional binding must be of Optional type

反对以下代码:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var imageView: UIImageView!
var dynamicAnimator = UIDynamicAnimator()

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    if let dynamicAnimator = UIDynamicAnimator(referenceView: self.view) {
        // creating and adding a gravity behaviour
        let gravityBehaviour = UIGravityBehavior(items: [self.imageView])
        dynamicAnimator.addBehavior(gravityBehaviour)

        // creating and adding a collision behaviour
        let collisionBehaviour = UICollisionBehavior(items: [self.imageView])
        collisionBehaviour.translatesReferenceBoundsIntoBoundary = true

        dynamicAnimator.addBehavior(collisionBehaviour)

        self.dynamicAnimator = dynamicAnimator
    }

}
}

该行的错误是:

if let dynamicAnimator = UIDynamicAnimator(referenceView: self.view) {

当我向dynamicAnimator添加问号以使其成为可选时,我会收到新的错误:

Expected '{' after 'if' condition
Variable binding in a condition requires an initializer
Braced block of statements is an unusual closure

我现在正在阅读可选类型以尝试理解它们,但这是本书中的代码。我已经检查了他们的论坛和勘误表部分,没有人提到这个问题。有人有什么想法吗?

由于

1 个答案:

答案 0 :(得分:2)

UIDynamicAnimator初始化程序不可用,就像某些类一样,因此您无法获取该行中的可选值。没有可选值,if let...结构没有意义,因此编译器不会让你写它。只是摆脱if部分,你就没事了。

let dynamicAnimator = UIDynamicAnimator(referenceView: self.view)
// no braces, either
// ...