Skip to content

Instantly share code, notes, and snippets.

@AliSoftware
Last active February 13, 2016 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AliSoftware/e6b931c1731f016e41fb to your computer and use it in GitHub Desktop.
Save AliSoftware/e6b931c1731f016e41fb to your computer and use it in GitHub Desktop.
Use of "Self" vs "self" in "static var" + generic protocol implementation
protocol Fooable {
static var staticBigSelf: String { get }
static var staticSmallSelf: String { get }
var instanceBigSelf: String { get }
var instanceSmallSelf: String { get }
init()
}
extension Fooable {
static var staticBigSelf: String { return String(Self) }
static var staticSmallSelf: String { return String(self) }
var instanceBigSelf: String { return String(Self) }
var instanceSmallSelf: String { return String(self) }
}
class ParentView: Fooable {
required init() {}
}
class ChildView: ParentView {
required init() {}
}
func fooableFactory<T where T: Fooable>() -> T {
print("Creating instance of \(T.self) with Self=\(T.staticBigSelf) & self=\(T.staticSmallSelf)")
return T()
}
func dump<T where T: Fooable>(instance: T) {
print("instance \(instance) with Self=\(instance.instanceBigSelf) & self=\(instance.instanceSmallSelf)")
}
let cv = fooableFactory() as ChildView // Prints: Creating instance of ChildView with Self=ParentView & self=ChildView
dump(cv) // Prints: instance ChildView with Self=ChildView & self=ChildView
ChildView.staticBigSelf // Prints: "ChildView"
ChildView.staticSmallSelf // Prints: "ChildView"
@AliSoftware
Copy link
Author

What puzzles me is that:

  • ChildView.staticBigSelf returns ChildView, letting us think that the Self in the staticBigSelf's default implementation is resolved dynamically in this case
  • But T.staticBigSelf in fooableFactory is always resolved as ParentView even when the generic T is resolved as ChildView (T.self=ChildView but T.staticBigSelf=ParentView) letting us think that T and Self are resolved statically in this case

@AliSoftware
Copy link
Author

For reference, this has been duly reported as Swift bug SR-617 in JIRA

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