美文网首页
Swift中的Self

Swift中的Self

作者: sasky2008 | 来源:发表于2018-11-05 15:17 被阅读12次

    Self 作为返回值

      protocol CustomInit {
        func customInit() -> Self
      }
    
    class MyAClass: CustomInit {
    
       var name: String?
    
       // return `Self`的自定义方法
       func customInit() -> Self {
         let result = type(of: self).init()
         result.name = name
         return result
       }
    
       // 不推荐使用的init方法
       func myErrorInit(_ name: String?) -> MyAClass {
         let result = MyAClass.init()
         result.name = name
         return result
       }
    
       // 便利构造器
       convenience init(_ name: String?) {
         self.init()
         self.name = name
       }
    
       required init() {}
    }
    

    一般作为返回值, 返回自己的类的对象.
    这种时候我们可以使用Self替代类名, 这样对于定义协议很有利.

    protocol CustomInit 便可以多个类同时使用, 而不会局限于一个class/struct
    

    有人问我为什么写了一行

    required init() {}
    

    这是因为Swift要保证当前类和子类都能响应这个init方法. 也就是type后面的init().
    这时候有两个方法解决, 一个是加一个required关键字, 另一个方法便是将此类, 设置为

    final class MyAClass: CustomInit {}
    

    相关文章

      网友评论

          本文标题:Swift中的Self

          本文链接:https://www.haomeiwen.com/subject/hlysxqtx.html