简体   繁体   English

在 swift 中检查多类型转换

[英]Check for Multiple Type Casting in swift

Currently I am trying to do multiple class casting to do some operation like UIBarButtonItem or UIControl.目前我正在尝试进行多类转换以执行一些操作,如 UIBarButtonItem 或 UIControl。

is there a way to do both on the same line?有没有办法在同一条线上同时进行? Like:像:

if let x = sender as? UIControl, sender as? UIBarButtonItem {
print (x)
}

I have tried many ways but still not able to cast multiple class in one line.我尝试了很多方法,但仍然无法在一行中投射多个类。

Thanks.谢谢。

Swift is a statically typed language. Swift是一种静态类型的语言。 All variables have a single type that's known at compile-time. 所有变量都有一个在编译时就已知的类型。 Unlike dynamically typed languages (Python, Ruby, Smalltalk, Javascript, etc.), there's no way to directly do something like this: 与动态类型的语言(Python,Ruby,Smalltalk,Javascript等)不同,无法直接执行以下操作:

let x: String or Int
if condition { x = 123 }
else { x = "string" }

Imagine if it were possible: what would be the value of sqrt(x) if x was a String ? 想象一下是否有可能:如果xStringsqrt(x)的值是多少? What would be the value of x.uppercased() if x was an Int ? 如果x是一个Int ,则x.uppercased()的值是x.uppercased()

Instead, such "OR types" are encoded as either enums (who explicitly enumerate all supported members as cases with associated values), or as protocols. 而是将此类“ OR类型”编码为枚举(将所有受支持的成员明确枚举为具有关联值的案例)或协议。 Protocols have the added benefit that they explicitly state what behaviour is expected out of conforming types, and they're open ended to conformance by future types. 协议具有额外的好处,即它们明确声明了在符合类型之外的行为,并且对于将来的类型而言,它们是开放式的。

The most general protocol is Any , which captures ALL types. 最通用的协议是Any ,它捕获所有类型。 Its generality is both its strength and its weakness. 它的普遍性既是它的优势,也是它的劣势。 While you can assign any value to it, you can do very little with it directly, because there are very few operations supported by all types. 尽管可以为它分配任何值,但是由于几乎所有类型支持很少的操作,因此您几乎不能直接对其进行任何操作。

In your case, it would be most fitting to make a protocol, add to it whatever functionality you want to access, and conform your desired types to it. 在您的情况下,最合适的方法是创建一个协议,向其中添加您要访问的任何功能,并使所需的类型符合该协议。

protocol Fooable {
     func foo()
}

extension UIControl: Fooable { 
     func foo() {
          print("I am a UIControl!")
     }
}

extension UIBarButtonItem: Fooable {
     func foo() {
          print("I am a UIBarButtonItem!")
     }
}

if let fooableThing = sender as? Fooable {
    fooableThing.foo()
}

You can use switch for Type Casting:您可以使用switch进行类型转换:

switch sender {
case let x as UIControl:
    print(x)
case let x UIBarButtonItem:
    print(x)
default:
    break
}

More info in Swift docs here: https://docs.swift.org/swift-book/LanguageGuide/TypeCasting.html Swift 文档中的更多信息在这里: https ://docs.swift.org/swift-book/LanguageGuide/TypeCasting.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM