swift - 编译器不将私有(private)扩展中的方法识别为私有(private)

标签 swift

我有以下代码:

class C {
    private enum E {
        // ...
    }
}

private extension C {
    func f(e: E) {    // error: Method must be declared private because its parameter uses a private type
        // ...
    }
}

如果我将错误方法设置为 private,编译器错误就会消失。我想知道这是 Swift 中的错误还是我没有得到什么?

最佳答案

在顶层,private 等同于 fileprivate – 因为 private 意味着只能在封闭范围内访问(以及同一个文件)扩展),并且在顶层,文件那个范围。

所以你这里的内容等同于:

class C {
    private enum E {
        // ...
    }
}

<b>fileprivate</b> extension C {
    // error: Method must be declared private because its parameter uses a private type.
    func f(e: E) { 
        // ...
    }
}

(出于这个原因,为了清楚起见,我总是在顶层写 fileprivate 而不是 private)

这让问题更容易理解——扩展方法f默认是fileprivate,因此可以在整个文件范围内访问,但它的参数是类型化的作为 E,它只能在类 C 的范围内访问。

正如您所发现的,您可以将 f 标记为 private:

class C {
  private enum E {
    // ...
  }
}

fileprivate extension C {
  <b>private</b> func f(e: E) {
    // ...
  }
}

或者将E标记为fileprivate:

class C {
  <b>fileprivate</b> enum E {
    // ...
  }
}

fileprivate extension C {
  func f(e: E) {
    // ...
  }
}

为了解决扩展方法 f 与其参数类型 E 具有相同可见性的问题。

关于swift - 编译器不将私有(private)扩展中的方法识别为私有(private),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51770221/

相关文章:

ios - 组合框架序列化异步操作

swift - 在快速点击按钮时显示上下文菜单

ios - 如何使 UITableView 的第一行成为一个部分的标题?

ios - 在 tableViewController 中接收 Firebase autoId

ios - 我在他的类中设置 UITableViewCell 颜色后,它的颜色不再保持不变

ios - 如何从具有图像的自定义栏按钮项目中删除右填充/边距/空间?

ios - 查询 NearGeoPoint 返回空对象

objective-c - Objective C 扩展等同于 Swift 扩展?

ios - swift Gmail API : Try to send message gives error -1001

swift SKSpriteNode : Chaining Sprites by Image Feature