Skip to content

Instantly share code, notes, and snippets.

@mrh-is
Last active March 30, 2018 18:23
Show Gist options
  • Save mrh-is/e6ac28c40b52259ce8ee8275f4d525ad to your computer and use it in GitHub Desktop.
Save mrh-is/e6ac28c40b52259ce8ee8275f4d525ad to your computer and use it in GitHub Desktop.
import Foundation
protocol ObjCConvertible {}
extension String: ObjCConvertible {}
extension Int: ObjCConvertible {}
extension Double: ObjCConvertible {}
extension Bool: ObjCConvertible {}
func objCMethod(_ dict: [String: AnyObject]) {
print(dict)
}
func passToObjC(_ dict: [String: ObjCConvertible]) {
objCMethod(dict as [String: AnyObject])
}
passToObjC(["a": "b", "c": 1])
@mrh-is
Copy link
Author

mrh-is commented Mar 30, 2018

Sugar for building [String: AnyObject] dictionaries from Swift, mostly for passing to ObjC.

This works great for things that are actually _ObjectiveCBridgeable! Compiler magic does the boxing the right way. But anything else (custom structs/enums, other non-ObjC stuff) will get passed along also, and blow up when you try to touch them from ObjC.
Be careful with this, and only ever let things you know to be safely representable in ObjC conform to ObjCConvertible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment