为什么我可以在操场上设置私人场地 [英] Why I can set private field in playground

查看:142
本文介绍了为什么我可以在操场上设置私人场地的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Vehicle类,其中有一个名为_odometer private 字段,然后,我有一个名为odometer的计算属性(它具有setter和getter)./p>

我认为_odometer不能设置,因为它是 private 字段,但是在操场上可以设置,为什么?这是我在操场上的代码:

如您所见,我创建了一个名为volvoVehicle实例.默认情况下,_odometer是500,但是我可以直接在volvo上将_odometer设置为 0 ,当打印出里程表"时,它是 0 . 为什么,我可以设置私有字段吗?

解决方案

Swift private在语义上与其他OO语言略有不同,它是源文件专用的.

Swift访问控制中:

私有访问将实体的使用限制为自己定义 源文件.使用私有访问权限隐藏实施细节 特定功能.

I have a simple Vehicle class which has a private field named _odometer, then, I have a computed-property named odometer(it has setter & getter).

I think _odometer should not be able to set since it is a private field, but in playground, it can be set, why? Here is my code in play ground:

As you can see, I created an instance of Vehicle named volvo. By default _odometer is 500, but I can directly set _odometer to 0 on volvo, when print out the 'odometer', it is 0. WHY I can set private field?

解决方案

Swift private is slightly semantically different than in other OO languages, it is private to the source file.

In Swift Access Control:

Private access restricts the use of an entity to its own defining source file. Use private access to hide the implementation details of a specific piece of functionality.

这篇关于为什么我可以在操场上设置私人场地的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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