Last active
January 8, 2016 12:02
-
-
Save dwineman/d6c56ec0c0e2fdb761db to your computer and use it in GitHub Desktop.
Swift allows you to call instance methods from other instance methods with no scope prefix, indistinguishably from function calls. This leads to the dangerous situation of function calls being shadowed when identically-named instance methods are added to a base class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Derived class contains an instance method that calls a function foo() in its scope. | |
class Base {} | |
func foo() -> String { | |
return "function foo()" | |
} | |
class Derived: Base { | |
func bar() -> String { | |
return foo() | |
} | |
} | |
var f = Derived() | |
f.bar() // returns "function foo()" | |
// But later, perhaps in a subsequent framework version or a class extension, the base class | |
// is updated by adding an instance method also called foo(). | |
// The behavior of the derived class now changes, because method foo() shadows function foo(): | |
class Base { | |
func foo() -> String { | |
return "method Base.foo()" | |
} | |
} | |
f.bar() // returns "method Base.foo()" | |
// Unfortunately, you can't opt out of the danger by choosing not to use this feature. Any | |
// function call in a class with one or more superclasses or extensions you don't control | |
// is at risk. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Well, I guess that settles that.