2014-11-13 46 views
2

我經歷O'Reilly的飛速發展與可可和正在以下錯誤:問題與可選類型和UIDynamicAnimator

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 

我讀了,現在就可選類型,試圖理解他們,但是這是直接從書的代碼。我檢查了他們的論壇和勘誤部分,沒有人提到過這個問題。有人有主意嗎?

感謝

回答

2

UIDynamicAnimator初始化不failable,就像他們是一些類,這樣你就不會又回到該行的可選值。沒有可選的值,if let...構造沒有意義,所以編譯器不會讓你編寫它。只要擺脫if部分,你會沒事的。

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

謝謝你的幫助。 – ckbrumb