Search code examples
objective-cswiftlanguage-interoperability

How to access private members of an Objective-C class from a Swift extension?


I'm trying to extend an Objective-C class in Swift and make it conform to the Equatable protocol. This requires to access some private members of the extended class, which the compiler doesn't let me do. What is the correct way to do it without making the private members public?

My Swift code:

import Foundation

extension ShortDate : Equatable {  }

public func == (lhs: ShortDate, rhs: ShortDate) -> Bool {
    if (lhs.components.year == rhs.components.year)
        && (lhs.components.month == rhs.components.month)
        && (lhs.components.day == rhs.components.day) {
            return true;
    }
    return false;
}

Objective-C:

@interface ShortDate : NSObject<NSCopying, NSCoding> {
    NSDate           *inner;
    NSDateComponents *components; // The date split into components.
}

...

@end

The error I'm getting:

ShortDate.swift:26:9: 'ShortDate' does not have a member named 'components'


Solution

  • I believe that there is no way to access Objective-C instance variables from Swift. Only Objective-C properties get mapped to Swift properties.