Private value can still be accessed from outside - swift

I am still bit confused about the scope, I think the variables can only be accessed within its scope, that's what I've understand in a general way
class Car {
let manufacturer: String
private(set) var color: String
init() {
manufacturer = "Ford"
color = "Black"
}
func changeColor(color: String){
self.color = color
}
}
var carOfTim = Car()
carOfTim.changeColor("Red") // only "changeColor" fun can update the color
print(carOfTim.color)
//why I can do this?
carOfTim.color = "Green"
print(carOfTim.color) // it prints the "Green"!
Question: I think the private variable color can only be accessed by thechangeColor function, because changeColor has the same scope with color. But carOfTim.color = "Green" can still update the color variable, why?
Guess: Since I used the Xcode playground, everything is inputted into the same plain "terminal", therefore all of them might have the same scope, if I put the Car class into a different folder, carOfTim.color = "Green" may not working anymore.
Please correct me if I'm wrong. Thanks a lot for your time and help.

In Swift, private is scoped to the source file, not to the declaring entity. That's a design decision.
From the documentation:
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.
...
NOTE
Private access in Swift differs from private access in most other languages, as it’s scoped to the enclosing source file rather than to the enclosing declaration. This means that a type can access any private entities that are defined in the same source file as itself, but an extension cannot access that type’s private members if it’s defined in a separate source file.
And in the examples below (bold is mine):
However, the access level for the numberOfEdits property is marked with a private(set) modifier to indicate that the property should be settable only from within the same source file as the TrackedString structure’s definition.

Related

private Helper class with public static func access modifier

I think I probably have some blind spot. The following code in test target actually works that I thought it should not: (MyHelper is private already, but the caller still can use myHelperFunc())
// both MyClass and MyHelper are in the same file
class MyClass: XCTestCase {
func testDoWork() {
MyHelper.myHelperFunc()
}
}
private class MyHelper {
static func myHelperFunc() -> String {
return "something"
}
}
If I move the code to main target (delete the XCTestCase), compiler immediately flag MyHelper is not accessible that seems the right behavior? Is there something specific for test target that I missed?
private at file scope is equivalent to fileprivate.
#testable import makes internal code accessible to a test target.
Access Levels in The Swift Programming Language explains how private works:
Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file.
"The enclosing declaration" of MyHelper is "the file." This is perhaps a bit more clearly stated in the Declaration Modifiers section of the Swift Language Reference:
private
Apply this modifier to a declaration to indicate the declaration can be accessed only by code within the declaration’s immediate enclosing scope.
Again, the "enclosing scope" of MyHelper is the file. If MyHelper were enclosed in some other class, then it would be limited to that scope rather than the whole file:
// Things change if MyHelper has a different enclosing scope than MyClass.
class MyClass {
func testDoWork() {
MyHelper.myHelperFunc() // Cannot find 'MyHelper' in scope
}
}
class C {
// MyClass can't access C.MyHelper now.
private class MyHelper {
static func myHelperFunc() -> String {
return "something"
}
}
}
In your example, myHelperFunc() has no annotation, so it initially receives the default level of internal. This is noted in Access Levels again:
Default Access Levels
All entities in your code (with a few specific exceptions, as described later in this chapter) have a default access level of internal if you don’t specify an explicit access level yourself.
However, as noted in "Guiding Principle of Access Levels:"
No entity can be defined in terms of another entity that has a lower (more restrictive) access level.
It is not allowed for MyHelper.myHelperFunc() to have a broader access level than its encoding type (MyHelper), so it's limited to file scope (which is effectively the same as fileprivate).

Hiding property setters by class in Swift

I would like to hide some property setters and initializers on my Swift model objects. These are reference data that the server provides, and under no circumstances should they be created or modified by the application. This is simple enough in Swift.
However, there is application in my project (a separate target) that needs to break this rule. It is a tool I use to populate the data in bulk, so of course needs to be able to initialize new model objects and set their properties.
What are my options for accomplishing this? I would rather not use a completely new project since it will mean a lot of code duplication. Is there some language-level way to keep this mutability hidden from one application but available to another?
If you declare a property with the let keyword. It can then only be set in the init of the type.
You can also declare a private setter to make the property readonly from the caller of the type but read/write inside the type
struct Foo {
private(set) var bar: Bool = true
func toggle() {
bar.toggle()
}
}
var foo = Foo()
let barState = foo.bar // This works
foo.toggle() // This works too
foo.bar.toggle() // This will make a compile time error

What is the use of open variables over public variables which are stored? [duplicate]

This question already has answers here:
What is the 'open' keyword in Swift?
(5 answers)
Closed 3 years ago.
I have checking out some code and I came across code that is marked as open for a variable and it is a stored property. What kind of use does open have over public in this case? This is some made up code:
open class God {
open var hasSuperPowers = true
}
class HalfGod: God {
override var hasSuperPowers = false
}
This does not compile: Cannot override with a stored property 'hasSuperPowers'. This is because the variable is stored.
My question is therefore: What difference does it make when marking my stored property either open or public? Can I do something with an open stored property, which I can not do with a public stored property?
I would expect xCode would give me warning that marking hasSuperPowers as open would have no effect and would falsely imply to other people that they can override this variable. Ofcourse, this only applies when someone can confirm me that open or public does not make any difference.
Edit: I got now three people showing me the difference between open and var. Does my question even get read? Again:
What difference does it make when marking my stored property either open or public? Again: STORED PROPERTY
You can override a property but not with a stored property. When overriding properties, you have to use a computed property, e.g.:
A class with a stored property:
open class God {
open var hasSuperPowers = true
}
The property can be overriden only with a computed property:
class HalfGod: God {
override var hasSuperPowers: Bool {
didSet {
print("\(oldValue) -> \(hasSuperPowers)")
}
}
}
or
class HalfGod: God {
var hasPowers: Bool = false
override var hasSuperPowers: Bool {
get {
return hasPowers
}
set {
hasPowers = newValue
}
}
}
You can override properties from other modules only if they are open. public properties cannot be overriden from other modules.
From the link in the comment:
An open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.
A public class is accessible but not subclassable outside of the defining module. A public class member is accessible but not overridable outside of the defining module.
What difference does it make when marking my stored property either open or public?
If its marked public, then you cannot override the member outside the defining module.
Can I do something with an open stored property, which I can not do with a public stored property?
You can subclass it outside of the defining module.

How can I give clients read-access to an array in Swift? [duplicate]

In Swift, what is the conventional way to define the common pattern where a property is to be externally readonly, but modifiable internally by the class (and subclasses) that own it.
In Objective-C, there are the following options:
Declare the property as readonly in the interface and use a class extension to access the property internally. This is message-based access, hence it works nicely with KVO, atomicity, etc.
Declare the property as readonly in the interface, but access the backing ivar internally. As the default access for an ivar is protected, this works nicely in a class hierarchy, where subclasses will also be able to modify the value, but the field is otherwise readonly.
In Java the convention is:
Declare a protected field, and implement a public, read-only getter (method).
What is the idiom for Swift?
Given a class property, you can specify a different access level by prefixing the property declaration with the access modifier followed by get or set between parenthesis. For example, a class property with a public getter and a private setter will be declared as:
private(set) public var readonlyProperty: Int
Suggested reading: Getters and Setters
Martin's considerations about accessibility level are still valid - i.e. there's no protected modifier, internal restricts access to the module only, private to the current file only, and public with no restrictions.
Swift 3 notes
2 new access modifiers, fileprivate and open have been added to the language, while private and public have been slightly modified:
open applies to class and class members only: it's used to allow a class to be subclassed or a member to be overridden outside of the module where they are defined. public instead makes the class or the member publicly accessible, but not inheritable or overridable
private now makes a member visible and accessible from the enclosing declaration only, whereas fileprivate to the entire file where it is contained
More details here.
As per #Antonio, we can use a single property to access as the readOnly property value publicly and readWrite privately. Below is my illustration:
class MyClass {
private(set) public var publicReadOnly: Int = 10
//as below, we can modify the value within same class which is private access
func increment() {
publicReadOnly += 1
}
func decrement() {
publicReadOnly -= 1
}
}
let object = MyClass()
print("Initial valule: \(object.publicReadOnly)")
//For below line we get the compile error saying : "Left side of mutating operator isn't mutable: 'publicReadOnly' setter is inaccessible"
//object.publicReadOnly += 1
object.increment()
print("After increment method call: \(object.publicReadOnly)")
object.decrement()
print("After decrement method call: \(object.publicReadOnly)")
And here is the output:
Initial valule: 10
After increment method call: 11
After decrement method call: 10

AS3 - Private Object. Make property as read only

I have a object property in my Class which is private and marked as read-only.
private var readOnlyObj:Object;
I can only access it with a get method:
public function get readOnly(){ return readOnlyObj }
I can access it by:
var objClass = new MyClass();
trace(objClass.readOnly)
And if i'll try to modify it:
objClass.readOnly = new Object();
I'll get an error:
Error# Property is read only.
Now my question is:
How do I set the properties of my readOnlyObj as read-only?
If I have set the object in the constructor:
readOnlyObj["property1"] = 0;
And modify that property by:
objClass.readOnly["property1"] = 2;
It is valid. I want set the property1 to a read-only property. Is this possible? Thank You!
You can do this by returning a duplicate of the original object and not the object itself.
The transform properties of DisplayObjects work like this: you can get the object property from a get function and can modify the object, but such modification has no effect until you pass the modified object back to the set function.
In your case, there's no way to give the object back (no setter) and by returning a copy (commonly called 'clone') from the getter, there is no way to modify the object property from outside, because the returned reference reference the newly created independent clone, essentially making the internal object constant.
What you are asking is not possible and only yield the answer "no" if on the other hand you asked about how to achieve that functionality then there would be a few answer possible.
First of all given your code and the problem at hand it is clear that you misunderstand the class scope. You set:
private var readOnlyObj:Object;
As read only while it's really not the object you want to protect, it's its properties. So readOnlyObj should really not even be visible and accessible.
Now that readOnlyObj is private and not accessible, you can put together a simple method to retrieve properties:
public function getProperty(name:String):*
{
if(readOnlyObj[name] != undefined)
{
return readOnlyObj[name];
}
return null;
}
It might also be useful to know how to put together a public setter that cannot be used externally.
Create an internal Boolean variable (only with true package), then internally set that variable to true before setting the property then set it back to false. Since externally that boolean cannot be set you end up with a public setter that cannot be used externally.
internal var allowSetter:Boolean;
public function set whatever(value:*):void
{
if(allowSetter)
{
//set property ect...
allowSetter = false;
}
}
You can't really do this, at least in the way you describe. You can of course make your readOnly object a custom class instance that only has read-only properties, but you can't freeze a dynamic Object instance.