[swift-users] How self automatically becomes Self type if the function's return type is Self?
Zhao Xin
owenzx at gmail.com
Sun Aug 28 12:13:11 CDT 2016
Thanks, Kenny. I found that self is dynamic. Despite the original type of
variable. See below code, `test` variable. It was Foo type, but it can be
Bar as well.
class Foo { func printType() { print(type(of:self)) } func printSelf() {
print(self) } } class Bar:Foo { } let foo = Foo() foo.printType() // Foo
foo.printSelf() // Foo let bar = Bar() bar.printType() // Bar
bar.printSelf() // Bar var test = Foo() test.printType() // Foo
test.printSelf() // Foo test = Bar() test.printType() // Bar
test.printSelf() // Bar
So now I think that self should always be Self type.
Zhaoxin
On Sun, Aug 28, 2016 at 2:05 PM, Kenny Leung via swift-users <
swift-users at swift.org> wrote:
> There is no magic happening here. Rather, I think it’s a misunderstanding
> of what -> Self means. Self is a placeholder for “the current type”, just
> like self is a placeholder for “the current instance”. So when you declare
> -> Self, the correct thing to do is an instance of Self, which is self.
>
> You can see this if you replace Self with String.
>
> protocol Foo {
> func instance() -> String
> }
>
> class Bar: Foo {
> func instance() -> String {
> return “blah"
> }
> }
>
> -Kenny
>
>
> > On Aug 27, 2016, at 7:05 AM, Zhao Xin via swift-users <
> swift-users at swift.org> wrote:
> >
> > See the code:
> >
> > protocol Foo {
> > func instance() -> Self
> > }
> >
> > class Bar: Foo {
> > func instance() -> Self {
> > return self // Declaration: let `self`: Self
> > }
> > func other() {
> > let i = self // Declaration: let `self`: Bar
> > }
> > }
> >
> > How does it happen?
> >
> > Zhaoxin
> > _______________________________________________
> > swift-users mailing list
> > swift-users at swift.org
> > https://lists.swift.org/mailman/listinfo/swift-users
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160829/233bb630/attachment.html>
More information about the swift-users
mailing list