i created a helper function:
return value != nil ? (value as! T) : nil
to use it like this:
let dog = cast(any, to: Dog.self)
the idea is that it is a “stricter” version of the “as?” operator:
let dog = any as? Dog // will return nil when a car is passed, i want a crash here in this case.
let dog = any != nil ? (any as! Dog) // so i want this: if it is not nil it must be a dog (*)
let dog = cast(any, to: Dog.self) // a bit shorter and less visually disturbing
(* note that the extra parens around “(any as! Dog)” are there to stop a warning).
now the question, probably to swift designers, but anyone’s input is welcome:
this cast function is not as nice as the built-in “as?” operator. i can not pass “Dog” alone in this context, I have to put it as “Dog.self”. is there some deep logic why it is so? i believe in this context “Dog” alone can not mean anything else (useful), what harm it would make to treat “Dog” here as if “Dog.self” was passed?
Powered by WPeMatico