Reinier Melian Reinier Melian - 1 year ago 59
Swift Question

Can I define methods for properties on a Swift class like in Objective-C?

Is it possible to define a method for a property on a Swift class

For example, I have a class named Test in Objective-C, and this class has one property called



@interface Test : NSObject

@property (nonatomic, readonly) NSString *testProperty;


I define a getter method in the implementation for this property:


#import "Test.h"

@implementation Test

return @"testing property like method";


How can I do the same in Swift? If make the class in Swift,

import UIKit

class Test: NSObject {
var testProperty : String?

func testProperty() -> String {
return "testing property like method"


then I receive an error:

"Invalid redeclaration of testProperty()"

Answer Source

These are called Computed properties


var testProperty: String {
    return "testing property like method"


class ClassA: NSObject {
    var testProperty: String {
        return "This is Class A"

class ClassB: ClassA {
    override var testProperty: String {
        return "This is Class B"

let test = ClassB()
print(test.testPropery) // prints "This is Class B"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download