You can do the very same trick that you would do if your project was in
Objective-C.
Create a header file and put the declaration of a category on the class, along with the declaration of the private methods you wish to expose. Then, tell the Swift compiler to import this bridging header.
For demonstration purposes, I'm going to poke around in the internals of NSBigMutableString
, a private subclass of NSMutableString
, and I will call its _isMarkedAsImmutable
method.
Note that here, the entire class itself is private, hence I have to declare it as a subclass of its real superclass first. Because of this, I could have as well declared the method right in the declaration of the class itself; that, however, wouldn't have demonstrated the usage of the (Private)
trick-category.
If your class is public, then obviously you will only need the category, and you won't need to (re-)declare the class itself.
Bridge.h:
#import <Foundation/Foundation.h>
@interface NSMutableString (Private)
- (BOOL)_isMarkedAsImmutable; // this is a lie
@end
@interface NSBigMutableString : NSMutableString
@end
s.swift:
let s = NSBigMutableString()
println(s._isMarkedAsImmutable())
Compile and run:
$ xcrun -sdk macosx swiftc -o foo -import-objc-header Bridge.h s.swift
$ ./foo
false
$
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…