gpt4 book ai didi

ios - swift 5 : Binary operator '==' cannot be applied to operands of type 'AnyObject?' and 'UIView?'

转载 作者:行者123 更新时间:2023-11-28 09:38:59 29 4
gpt4 key购买 nike

我使用 Swift 5 并尝试测试 someView 的所有 NSLayoutContraints 是否与某些 otherView 相关:

@IBOutlet var someView: UIView!
@IBOutlet var otherView: UIView!

for constraint in someView.constraints {
if (constraint.firstItem == otherView) {
...
}
}

此代码因以下错误而失败:

Binary operator '==' cannot be applied to operands of type 'AnyObject?' and 'UIView?'

关于 Swift 中的类型和运算符还有很多其他问题,但我仍然不明白为什么会出现此错误以及如何解决它:

  • constraint.firstItemAnyObject? 类型。所以它要么是 nil 要么是 AnyObject
  • 类型的对象
  • otherViewUIView! 类型,所以它保证不是 nil,对吗?

据我所知,AnyObject 是所有类隐式遵守的协议(protocol)。因此,将任何对象与 AnyObject? 进行比较应该不是问题,不是吗?

那么,为什么 constraint.firstItem == otherView 不起作用?解决它的正确方法是什么?

奖励问题:为什么错误消息说的是 UIView? 而不是 UIView!

最佳答案

只需使用 === 而不是 ==,即

if (constraint.firstItem === otherView) {
....
}

===(::)

Returns a Boolean value indicating whether two references point to the same object instance.

This operator tests whether two instances have the same identity, not the same value. For value equality, see the equal-to operator (==) and the Equatable protocol.

关于ios - swift 5 : Binary operator '==' cannot be applied to operands of type 'AnyObject?' and 'UIView?' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57493970/

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