Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for Multiple Type Casting in swift

Tags:

ios

swift

Currently I am trying to do multiple class casting to do some operation like UIBarButtonItem or 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.

like image 698
topgun Avatar asked Feb 05 '26 02:02

topgun


1 Answers

Swift is a statically typed language. 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:

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? What would be the value of x.uppercased() if x was an Int?

Instead, such "OR types" are encoded as either enums (who explicitly enumerate all supported members as cases with associated values), or as protocols. 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. 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()
}
like image 97
Alexander Avatar answered Feb 07 '26 16:02

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!