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

I am trying to extend the Obj-C class in Swift and make it compatible with the Equatable protocoll. This requires access to some private members of the extended class, which the compiler does not allow me. What is the right way to do this without opening private members?

Swift:

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

Error:

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

+4
source share
2 answers

I believe there is no way to access Objective-C instance variables from Swift. Only Objective-C properties are displayed in Swift properties.

+3
source

, SDK, . , . , :

extension ObjcClass {
    func getPrivateVariable() -> String? {
        return value(forKey: "privateVariable") as? String
    }

    open override func value(forUndefinedKey key: String) -> Any? {
        if key == "privateVariable" {
            return nil
        }
        return super.value(forUndefinedKey: key)
    }
}

value(forUndefinedKey:) . value(forKey:) , , value(forUndefinedKey:) .

0

All Articles