2017-05-04 63 views
1

我想使一個迅速的3結構符合_ObjectiveCBridgeable,但我不知道還需要什麼來滿足協議。下面是我的結構和_ObjectiveCBridgeable一致性。我錯過了一些東西,但我不確定它是什麼。swift 3 _ObjectiveCBridgeable一致性

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 

回答

1

由於下劃線告訴你,_ObjectiveCBridgeable是私人的。其目的是「滿足將Objective-C對象類型橋接到Swift值類型的特定需求」。你不能把它用於你自己的類型;它通過「引擎蓋下的編譯器魔術」來工作。

有一個proposal on the table提供公共版本,但它尚未實施。

+0

但你可能想看看http://stackoverflow.com/questions/38837198/define-struct-that-is-treated-like-a-class-in-swift(其中你的問題可能是,一個副本)。 – matt

+0

好吧,Xcode說我需要實現類型'(Box._ObjectiveCType?) - > Box'的函數'_unconditionallyBridgeFromObjectiveC';但我對此感到困惑。 – DerrickHo328

+0

我意識到它是私有的,但在以前版本的swift中起作用。 – DerrickHo328