gpt4 book ai didi

cocoa - 可选类型和 UIDynamicAnimator 的问题

转载 作者:可可西里 更新时间:2023-11-01 01:43:17 26 4
gpt4 key购买 nike

我正在阅读 O'Reilly 的 Swift Development with Cocoa 并收到以下错误:

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

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

谢谢

最佳答案

UIDynamicAnimator 初始化器不是可失败的,就像它们用于某些类一样,因此您不会在该行中返回可选值。如果没有可选值,if let... 结构就没有意义,因此编译器不允许您这样写。去掉 if 部分就可以了。

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

关于cocoa - 可选类型和 UIDynamicAnimator 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26919822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com