扩展在Swift的类扩展中定义的Private类

时间:2018-09-29 16:56:31

标签: swift

TL; DR

是否可以扩展私有且定义为扩展的类,即NewsParser


相关文档

swift2 - Extension of a nested type in Swift - Stack Overflow讨论了类似的情况,但嵌套类类型不是私有的。


我有一个NewsPost班:

class NewsPost {
  var title: String?
  var author: String?
  var mainContent: NSAttributedString?

  var data: Data? {
    didSet {
      let newsParser = NewsParser(delegate: self)
      newsParser.parse()
    }
  }

  // Init methods and other stuff...
}

还有一个NewsPost拥有的类NewsParser :(在另一个Swift文件中,但是由于SR-631,这似乎不是一个因素)

private extension NewsPost {
  private class NewsParser {
    weak var delegate: NewsPost?
    // Other properties for parsing...

    init(delegate: NewsPost) {
      self.delegate = delegate
    }

    func parse() {
      // parse the delegate.data and update properties in delegate (NewsPost instance)
    }

    // Other methods to be called for parsing...
  }
}

但是似乎无法扩展NewsPost.NewsParser

以下尝试不起作用:

尝试1

  

错误:由于“文件私有”保护级别,无法访问“ NewsParser”

private extension NewsPost { // Notice the "private" prefix
  class NewsParser {
    weak var delegate: NewsPost?
    //Other properties for parsing...

    init(delegate: NewsPost) {
      self.delegate = delegate
    }

    func parse() {
      // parse the delegate.data and update properties in delegate (NewsPost instance)
    }
    // Other methods to be called for parsing...
  }
}

NewsPost定义中发生错误:

var data: Data? {
    didSet {
        let newsParser = NewsParser(delegate: self) // error happens here
        newsParser.parse()
    }
}

尝试2

  

错误:由于“私有”保护级别,无法访问“ NewsParser”

extension NewsPost { 
    private class NewsParser { // Notice the "private" prefix
        var delegate: NewsPost
        // Other properties for parsing...

        func parse() {
            // parse the delegate.data and update properties in delegate (NewsPost instance)
        }

        // Other methods to be called for parsing...
    }
}

extension NewsPost.NewsParser { // error happens here
// extensions here...
// many kinds of errors happen here
}

是否可以扩展私有并定义扩展类,即NewsParser

1 个答案:

答案 0 :(得分:2)

我在操场上尝试了您的代码,它的工作原理就像是一个带有嵌套在私有扩展中的私有类的魅力:

这样称呼:

var str = "Hello, playground"
let post = NewsPost()
post.data = str.data(using: .utf8)

enter image description here

您的主要问题是,您可能在单独的文件中声明了 private 扩展名,而 private 表示扩展名是 fileprivate 。将您的扩展程序和您的NewsPost类放在同一文件中,您的错误应该消失了!

如果您真的想扩展NewsParser,则必须设置为内部扩展。 扩展名声明仅在文件范围内有效,因此,如果创建私有类,则无法扩展它。

请注意,内部嵌套类在目标外部不可见。因此,使用框架,您应该能够从UI代码中隐藏NewsParser类。