Reinier Melian Reinier Melian - 4 months ago 14
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

testProperty
of
NSString
type

Test.h

@interface Test : NSObject

@property (nonatomic, readonly) NSString *testProperty;

@end


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

Test.m

#import "Test.h"

@implementation Test

-(NSString*)testProperty
{
return @"testing property like method";
}

@end


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

These are called Computed properties https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html

Example

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

Subclass

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"