Suppose you have a set of buttons:
let views: [NSView] = [NSButton(), NSButton(), NSButton()]
You can use these casts:
let viewsAreButtons = views is [NSButton] // returns true let buttonsForSure = views as! [NSButton] // crashes if you are wrong let buttonsMaybe = views as? [NSButton] // optionally set
If you try to use as in the case of the switch, as shown below, this will not work. The compiler (Swift 1.2 Xcode 6.3b1) says: "You cannot use a Downcast template like [NSButton].
switch views { case let buttons as [NSButton]: println("Buttons") default: println("something else") }
What is this limitation? Create a radar with your use case. The Swift team really throws to listen to reviews. If you really want to make it work, you can define your own pattern matching operator. In this case, it will be something like this:
struct ButtonArray { } let isButtonArray = ButtonArray() func ~=(pattern: ButtonArray, value: [NSView]) -> Bool { return value is [NSButton] }
Then it works:
switch views { case isButtonArray: println("Buttons")
Try it on the playground. Hope this helps!
source share