Skip to content

Instantly share code, notes, and snippets.

@dwineman
Last active January 8, 2016 12:02
Show Gist options
  • Save dwineman/d6c56ec0c0e2fdb761db to your computer and use it in GitHub Desktop.
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.
// 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.
@dwineman
Copy link
Author

dwineman commented Jan 8, 2016

Well, I guess that settles that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment