Protocol里Self的应用.

protocol Pro{
    //指向一个父亲
    var parent:Self? { get }
    //指向多个孩子
    var chidren:Array<Self>? { get }
}

当在protocol里使用Self做为类型时,表示指向自身的类型.这个类一定在加final修饰,表示这个类已经是没有子类了.

final class Test:Pro {
    var parent: Test?
    var chidren: Array<Test>?
}

如果不加会出现以下错误提示:

protocol 'Pro' requirement 'chidren' cannot be satisfied by a non-final class ('Test') because it uses 'Self' in a non-parameter, non-result type position

但是,Self做为返回类型时,没有这样的限制

protocol Pro{
    // 返回自己
    func returnSelf() -> Self?
}
class Test:Pro {
    func returnSelf() -> Self? {
        return self //只能返回自身`self`,不能返回其它的相同类型.
    }
}

只能返回自身self,不能返回其它的相同类型.

//错误,示例
class Test:Pro {
    func returnSelf() -> Self? {
        return Test()  
    }
}

会出现以下错误提示

error: cannot convert return expression of type 'Test' to return type 'Self?'

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容