Swift中不再有`private init`吗? [英] No more `private init` in Swift?

查看:150
本文介绍了Swift中不再有`private init`吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了许多在Swift中使用private init来限制对象构造的引用(例如),但是当我尝试(在Xcode 7.2.1 Playground中)时似乎无法实现:

I saw a number of references to using private init in Swift to restrict object construction (e.g. this), yet it does not seem to be possible when I try (in Xcode 7.2.1 Playground):

class C {
    private init() {}
}

var c = C() // No errors.

我错过了什么吗,或者这实际上是一个错误吗?

Am I missing something or is this actually a bug?

推荐答案

您可能希望private将使用限制在类定义之内,但这不是它的作用.

You're probably expecting private to restrict the use to within the class definition, but that's not what it does.

private的定义是将实体的使用限制为自己定义的源文件".

The definition of private is to "restrict the use of an entity to its own defining source file".

从Swift书中,访问控制" 章.

From the Swift book, "Access Control" chapter.

在Swift 3中,fileprivate的用途与private相同,现在private的限制更为严格,因为它将实体的使用限制为封闭的声明"

As of Swift 3 fileprivate does what private used to and private is now more restrictive in that it "restricts the use of an entity to the enclosing declaration"

这篇关于Swift中不再有`private init`吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆