Runo Sahara
Runo Sahara

Reputation: 715

How do you override a readonly property to readwrite in sub class

I'd like to override a readonly property and make it read/writable.

The super class. This is in a framework so I can't rewrite it in Swift.

@interface AWSAbstractCognitoIdentityProvider : AWSAbstractIdentityProvider
@property (nonatomic, strong, readonly) NSString *providerName;
// (...)
@end

When I import the framework above, XCode7's interface preview was like this:

public class AWSAbstractCognitoIdentityProvider : AWSAbstractIdentityProvider {
    public var providerName: String! { get }
    // (...)
}

Now, the sub class definition. This class is defined in the app, so I'm trying to rewrite it in Swift.

// .h file
@interface AppIdentityProvider : AWSAbstractCognitoIdentityProvider
@end

// .m file
@interface AppIdentityProvider ()
@property (strong, atomic) NSString *providerName; // <=== THIS: Redeclare by removing readonly
@end

@implementation AppIdentityProvider
@synthesize providerName=_providerName;  // <=== and this

// ...
@end

How do you transcode the property above?

I tried the following:

public class AppIdentityProviderSwift: AWSAbstractCognitoIdentityProvider
{

    public override var providerName: String! {
        get { return super.providerName }
        set { super.providerName = newValue } // <== compile error, the property is read only
    }
    // (...)
}

Thanks.

Upvotes: 4

Views: 1688

Answers (2)

Jaycee
Jaycee

Reputation: 159

You can do the following in your code

private(set) var _providerName: String!

The above line will just apply private for set and would be internal for set, which in turn will give you readonly behaviour.

Upvotes: 1

Adam
Adam

Reputation: 26927

You could add a backing variable to your class. That should be fine if you don't need to call your superclass' setter.

class AppIdentityProviderSwift : AWSAbstractCognitoIdentityProvider {
    private final var _providerName : String!
    override var providerName: String! {
        get {
            return _providerName
        }
        set {
            _providerName = newValue
        }
    }
}

Upvotes: 2

Related Questions