Can't use private property in extensions in an

2019-02-21 23:53发布

I can't use private property in extension. My extension is in another file.

How can I use private property in extension?

标签: ios swift swift3
1条回答
太酷不给撩
2楼-- · 2019-02-22 00:02

The rules for using a property in an extension of your type aren't actually any different from the rules of using that property anywhere else.

If the property is declared private, it cannot be used anywhere except within the scope with which it has been declared. That means not even in the same file.

If the property is declared fileprivate, it can only be used within the file it is declared (and by anything in that file).

If the property is declared internal (the default), it can only be used within the module it is declared (and by anything in that file).

If the property is declared public or open, it can be used by anything within the module as well as outside of the module by files that import the module it is declared in.

There is not a way to declare a variable in such a way that it can be used by extensions of your type but not by other things outside the type. This is not actually a change from Swift 2 to Swift 3. This has always been the case. What you are looking for it what other languages call protected. Swift does not and has never had an equivalent of protected from other languages.

The closest you can get is declaring a type and all of its extensions in a single file and disallowing any other types or type extensions to be declared in that file. Then you can mark properties as fileprivate and use them by the extensions in that file. This still will not allow use of the property by extensions of that type outside of the file and it will not prevent a future developer from adding another type or an extension of another type in that file which uses the property.

查看更多
登录 后发表回答