First off all: sorry for the title, but I didn't now how to better formulate the meaning of my following question in a single phrase.While I was writing the following Swift code:if errorData.isMemberOfClass(UIAlertController) {    self.presentViewController(errorData, animated: true, completion: nil)} else {    /* Some other code */}for my personal project the compiler gave me this error:'AnyObject' is not convertible to 'UIAlertController'; did you mean to use 'as!' to force downcast?and it won't let me compiler any further if I would not change my code in to this:if errorData.isMemberOfClass(UIAlertController) {    self.presentViewController(errorData as! UIAlertController, animated: true, completion: nil)} else {    /* Some other code */}But I don't get this: if I make the program check the class of errorData(which, to be precise, is of class AnyObject) using the if statement why does it force me to force downcast against the type of class is supposed to be inside the if?In other words: doesn't the compiler already knows that inside the statement errorData is UIAlertController? If it wasn't the program continued in the else portion instead, so errorData could even be of class Int or String for example
Why doesn't the compiler assume the if statement condition is correct inside it?
swift language;if statement
Yes, the compiler could deduce the fact that the variable is of the expected type, since it was tested immediately before. And in fact this would be the next easiest thing to add to the code for data flow analysis.However, the compiler will never be able to deduce as much about the program as you can. Even such a (to you) completely obvious property as the type in this construct has to be programmed into it explicitly. No matter how much effort the compiler writers expend on the task, there will always be a condition which seems obvious to human uses but isn't at all obvious to the compiler. (The problem is compounded because human perception works adaptively. Make a compiler smarter, and users will begin to expect smarter things from it. Deductions that last year seemed pretty advanced will now seem routine, and new problems will seem as if the compiler should easily recognize that.)Therefore, you are merely observing the current boundary between what's theoretically possible, and what (in the opinion of the compiler writers) is worth doing. Don't be sad. In a couple years they will have added this logic, and by then you'll find something else unreasonable!