Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Created October 10, 2018 04:18
Show Gist options
  • Save IanKeen/8605dbaa51bdda51dfa995fd4cbdd8ee to your computer and use it in GitHub Desktop.
Save IanKeen/8605dbaa51bdda51dfa995fd4cbdd8ee to your computer and use it in GitHub Desktop.
AutoObjectiveCBridgeable
protocol AutoObjectiveCBridgeable: _ObjectiveCBridgeable where _ObjectiveCType == ObjcType {
associatedtype ObjcType
func toObjectiveC() -> ObjcType
static func fromObjectiveC(_ instance: ObjcType) -> Self
}
extension AutoObjectiveCBridgeable {
// MARK: - _ObjectiveCBridgeable
func _bridgeToObjectiveC() -> ObjcType {
return toObjectiveC()
}
static func _forceBridgeFromObjectiveC(_ source: ObjcType, result: inout Self?) {
if !_conditionallyBridgeFromObjectiveC(source, result: &result) {
fatalError("Unable to bridge \(ObjcType.self) to \(self)")
}
}
static func _conditionallyBridgeFromObjectiveC(_ source: ObjcType, result: inout Self?) -> Bool {
result = Self.fromObjectiveC(source)
return true
}
static func _unconditionallyBridgeFromObjectiveC(_ source: ObjcType?) -> Self {
var result: Self?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
struct Foo: AutoObjectiveCBridgeable {
let value: Int
func toObjectiveC() -> NSFoo {
return NSFoo(value: value)
}
static func fromObjectiveC(_ instance: NSFoo) -> Foo {
return Foo(value: instance.value)
}
}
class NSFoo: NSObject {
let value: NSInteger
init(value: NSInteger) {
self.value = value
}
}
let a = Foo(value: 42)
a.value // 42
(a as NSFoo).value // 42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment