Created
October 10, 2018 04:18
-
-
Save IanKeen/8605dbaa51bdda51dfa995fd4cbdd8ee to your computer and use it in GitHub Desktop.
AutoObjectiveCBridgeable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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! | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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