How to make the property “read-only” outside calls and “read-write” outside class?
Published in
2 min readJan 31, 2024
Here is the Swift implementation:
public class SomeClass {
// Read-Only Outside: Public getter, private setter
public private(set) var readOnlyOutside: Int
// Read-Write Outside: Public getter and setter
public var readWriteOutside: Int
init(readOnlyValue: Int, readWriteValue: Int) {
self.readOnlyOutside = readOnlyValue
self.readWriteOutside = readWriteValue
}
func updateReadOnlyValue(newValue: Int) {
// This method can change readOnlyOutside's value within the class.
self.readOnlyOutside = newValue
}
}
let instance = SomeClass(readOnlyValue: 5, readWriteValue: 10)
// Read-Only Outside
print(instance.readOnlyOutside) // Allowed, prints 5
// instance.readOnlyOutside = 15 // Not allowed, setter is private
// Read-Write Outside
print(instance.readWriteOutside) // Allowed, prints 10
instance.readWriteOutside = 20 // Allowed, changes the value to 20
print(instance.readWriteOutside) // Allowed, prints 20
instance.updateReadOnlyValue(newValue: 30) // Allowed, changes the value from 5 to 30
print(instance.readOnlyOutside) // Allowed, print 30
Here is an Objective C implementation:
// MyObjectiveCClass.h
#import <Foundation/Foundation.h>
@interface MyObjectiveCClass : NSObject
@property (nonatomic, readonly) NSInteger readOnlyOutside;
@property (nonatomic) NSInteger readWriteOutside;
- (instancetype)initWithReadOnlyValue:(NSInteger)readOnlyValue readWriteValue:(NSInteger)readWriteValue;
- (void)updateReadOnlyValue:(NSInteger)newValue;
@end
// MyObjectiveCClass.m
#import "MyObjectiveCClass.h"
@interface MyObjectiveCClass ()
@property (nonatomic, readwrite) NSInteger readOnlyOutside; // Private readwrite redeclaration
@end
@implementation MyObjectiveCClass
- (instancetype)initWithReadOnlyValue:(NSInteger)readOnlyValue readWriteValue:(NSInteger)readWriteValue {
self = [super init];
if (self) {
_readOnlyOutside = readOnlyValue;
_readWriteOutside = readWriteValue;
}
return self;
}
- (void)updateReadOnlyValue:(NSInteger)newValue {
_readOnlyOutside = newValue;
}
@end
// How to use
MyObjectiveCClass *instance = [[MyObjectiveCClass alloc] initWithReadOnlyValue:5 readWriteValue:10];
// Read-Only Outside
NSLog(@"%ld", (long)instance.readOnlyOutside); // Allowed, prints 5
// instance.readOnlyOutside = 15; // Not allowed, setter is private
// Read-Write Outside
NSLog(@"%ld", (long)instance.readWriteOutside); // Allowed, prints 10
instance.readWriteOutside = 20; // Allowed, changes the value to 20
NSLog(@"%ld", (long)instance.readWriteOutside); // Allowed, prints 20
[instance updateReadOnlyValue:30]; // Allowed, changes the value from 5 to 30
NSLog(@"%ld", (long)instance.readOnlyOutside); // Allowed, prints 30