2

I am trying to make a swift 3 struct conform to _ObjectiveCBridgeable but I am not sure what else I need to satisfy the protocol. Below is my struct and the _ObjectiveCBridgeable conformance. I am missing something but I am not sure what it is.

struct Box {
    let contents: Any
}

extension Box: _ObjectiveCBridgeable {
    typealias _ObjectiveCType = thing;

    init(fromObjectiveC source: _ObjectiveCType) {
        contents = source.contents
    }

    static func _isBridgedToObjectiveC() -> Bool {
        return true
    }
    static func _getObjectiveCType() -> Any.Type {
        return _ObjectiveCType.self
    }
    func _bridgeToObjectiveC() -> Box._ObjectiveCType {
        return thing(contents: self.contents)
    }

    static func _forceBridgeFromObjectiveC(_ source: Box._ObjectiveCType, result: inout Box?) {
        result = Box(contents: source.contents)
    }

    static func _conditionallyBridgeFromObjectiveC(_ source: Box._ObjectiveCType, result: inout Box?) -> Bool {
        _forceBridgeFromObjectiveC(source, result: &result)
        return true
    }
}

// Objc

@interface thing : NSObject
@property (readonly) id contents;
-(instancetype)initWithContents:(id)contents;
@end
@implementation thing
- (instancetype)initWithContents:(id)contents {
    if ((self = [super init])) {
        _contents = contents;
    }
    return self;
}
@end
DerrickHo328
  • 4,664
  • 7
  • 29
  • 50

1 Answers1

3

As the underscore tells you, _ObjectiveCBridgeable is private. Its purpose is "to accommodate the specific needs of bridging Objective-C object types to Swift value types". You cannot adopt it for your own types; it works by means of "compiler magic under the hood".

There is a proposal on the table to provide a public version, but it has not yet been implemented.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • But you might want to look at http://stackoverflow.com/questions/38837198/define-struct-that-is-treated-like-a-class-in-swift (of which your question is, perhaps, a duplicate). – matt May 04 '17 at 01:05
  • well, Xcode says I need to implement function '_unconditionallyBridgeFromObjectiveC' with type '(Box._ObjectiveCType?) -> Box'; But I am puzzled as to how. – DerrickHo328 May 04 '17 at 01:12
  • I realize it is private, but in previous versions of swift it worked. – DerrickHo328 May 04 '17 at 01:13