我最近将Xcode 6 beta 6更新为Xcode 6 beta 7,突然部分代码无法编译。我在我的代码中有这个函数,它给出了错误条件绑定中的Bound值必须是if let layoutManager = textView.layoutManager
行上的Optional type 。
func textTapped(recognizer: UITapGestureRecognizer){
self.textHasBeenTapped = true
if let textView = recognizer.view as? UITextView{
if let layoutManager = textView.layoutManager {
// rest of code
}
}
我已经尝试将textView设置为如下所示的可选类型(删除了初始错误),但它却提供了错误可选类型'CGFloat?'的值。没有打开;你的意思是用'!'在location.x = textView?.textContainerInset.left
行上的'?'?。如果我在!
之后插入?
或left
,则会给我错误: postfix'的操作数'!'应该有可选的类型;类型是'CGFloat'建议我删除'!'要么 '?'从而形成一种错误循环。
func textTapped(recognizer: UITapGestureRecognizer){
self.textHasBeenTapped = true
if let textView: UITextView? = recognizer.view as? UITextView{
if let layoutManager = textView?.layoutManager {
var location: CGPoint = recognizer.locationInView(textView)
location.x = textView?.textContainerInset.left
// rest of code
}
}
}
解决此问题的最佳方法是什么?
答案 0 :(得分:2)
您的原始问题实际上源于UITextView的layoutManager属性在beta 7中已更改,因此它不再是可选项。因此,保证不会为零,因此您不需要if let...
检查;你可以简单地使用这个值。
你制作的文字查看一个可选项只会导致更多的混乱;你应该把它作为非选择性的。
以下是我写的方式,并附有一些解释我的更改的评论。
func textTapped(recognizer: UITapGestureRecognizer) {
// You didn't need the self bit here.
textHasBeenTapped = true
// textView should be non-optional, and you don't need to bother
// specifying the type, as it can be inferred from the cast.
if let textView = recognizer.view as? UITextView {
// You don't need if let... here as layoutManager is now non-optional
let layoutManager = textView.layoutManager
// You don't need to specify the type here, as it can be inferred
// from the return type of locationInView
var location = recognizer.locationInView(textView)
location.x = textView.textContainerInset.left
// rest of code
}
}