gpt4 book ai didi

ios - Swift 3 - 如何验证对象的类类型

转载 作者:IT王子 更新时间:2023-10-29 07:46:08 25 4
gpt4 key购买 nike

这行代码用于 Swift 2,但现在在 Swift 3 中不正确。

if gestureRecognizer.isMember(of: UITapGestureRecognizer) { }

我收到此错误:预期的成员名称或构造函数调用在类型名称之后。

isMember(of:) 的正确使用方法是什么?

最佳答案

很可能,您不仅要检查类型,还要强制转换为该类型。在这种情况下,使用:

if let gestureRecognizer as? UITapGestureRecognizer { }
else { /* not a UITapGestureRecognizer */ }

Swift casting 运算符

这些运算符仅在 Swift 中可用,但在处理 Objective C 类型时仍然有效。

  • as运营商

    • The as operator performs a cast when it is known at compile time that the cast always succeeds, such as upcasting or bridging. Upcasting lets you use an expression as an instance of its type’s supertype, without using an intermediate variable.

    • 如果可能,这是最适合使用的运算符。它保证成功,无需担心展开可选或崩溃的风险。
  • as?运营商

    • The as? operator performs a conditional cast of the expression to the specified type. The as? operator returns an optional of the specified type. At runtime, if the cast succeeds, the value of expression is wrapped in an optional and returned; otherwise, the value returned is nil. If casting to the specified type is guaranteed to fail or is guaranteed to succeed, a compile-time error is raised.

    • 这是第二受欢迎的运算符。使用它来安全地处理无法执行转换运算符的情况。

  • as!运营商

    • The as! operator performs a forced cast of the expression to the specified type. The as! operator returns a value of the specified type, not an optional type. If the cast fails, a runtime error is raised. The behavior of x as! T is the same as the behavior of (x as? T)!.

    • 这是最不推荐使用的运算符。我强烈建议不要滥用它。尝试将表达式转换为不兼容的类型会使您的程序崩溃。


快速类型检查

如果您只想检查表达式的类型,而不强制转换为该类型,则可以使用这些方法。它们仅在 Swift 中可用,但在处理 Objective C 类型时仍然有效。

  • is运营商

    • is 运算符在运行时检查表达式是否可以转换为指定的类型。如果表达式可以转换为指定类型,则返回 true;否则,它返回 false
    • 适用于任何 Swift 类型,包括 Objective C 类型。
    • Swift 相当于 isKind(of:)
  • 使用 type(of:)

    • is 运算符不同,这可用于检查确切的类型,而不考虑子类。
    • 可以像这样使用:type(of: instance) == DesiredType.self
    • Swift 相当于 isMember(of:)

用于检查类型的遗留(Objective C)方法

这些都是关于NSObjectProtocol的方法.它们可以在 Swift 代码中使用,但它们仅适用于派生自 NSObjectProtocol 的类(例如 NSObject 的子类)。我建议不要使用这些,但我在这里提到它们是为了完整性

  • isKind(of:)

    • 返回一个 bool 值,指示接收者是给定类的实例还是从该类继承的任何类的实例
    • 在 Swift 中避免这种情况,改用 is 运算符。
  • isMember(of:)

    • 返回一个 bool 值,指示接收者是否是给定类的实例
    • 在 Swift 中避免这种情况,使用 type(of: instance) == DesiredType.self 代替。
  • conforms(to:)

    • 返回一个 bool 值,指示接收方是否符合给定的协议(protocol)。
    • 在 Swift 中避免这种情况,改用 is 运算符。

关于ios - Swift 3 - 如何验证对象的类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40388337/

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