Search code examples
objective-cswiftfoundation

readonly property for a foundation object in Swift


How do you refactor @property (readonly) NSDate *creationDate; into a Swift property of a struct?

struct structObject {

    var name: String
    var completed: Bool
    var creationDate: NSDate

}

Should the property be configured as a get property exclusively? In Objective-C the code is:

#import <Foundation/Foundation.h>

@interface ToDoItem : NSObject

@property NSString *itemName;
@property BOOL completed;
@property (readonly) NSDate *creationDate;

@end

Solution

  • There are a couple of different ways to do it.

    If you want it to be set at creation time and not changed afterwards, use let instead of var.

    If you want it to only be changed by the object's own methods, use private(set).