[swift-users] How self automatically becomes Self type if the function's return type is Self?

Kenny Leung kenny_leung at pobox.com
Sun Aug 28 01:05:49 CDT 2016


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



More information about the swift-users mailing list