Last active
August 29, 2015 14:06
-
-
Save aleclarson/58104cd6ca2e72707b91 to your computer and use it in GitHub Desktop.
Veil.swift
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
/// Veils a T as an NSObject. | |
public func veil <T> (value: T!) -> NSObject! { | |
if value == nil { return nil } | |
let value = value! | |
if let obj = value as? NSObject { return obj } | |
let obj = _Object() | |
if isObject(value) { obj.ref = Reference(cast(value), .Weak) } | |
else { obj.ref = Reference(_Value(value)) } | |
return obj | |
} | |
/// Unveils an NSObject as a T. | |
public func unveil <T> (var obj: AnyObject!) -> T! { | |
if obj == nil { return nil } | |
if obj is _Object { obj = (obj as _Object).ref.object } | |
if obj is _Value { return (obj as _Value).value as? T } | |
return obj as? T | |
} | |
/// An AnyObject disguised as an NSObject | |
class _Object : NSObject { | |
var ref: Reference<AnyObject>! | |
} | |
/// An Any disguised as an AnyObject | |
class _Value { | |
let value: Any | |
init (_ value: Any) { self.value = value } | |
} | |
func isObject <T> (value: T) -> Bool { | |
return reflect(value).objectIdentifier != nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A fantastic way to treat any value as an
NSObject
!This is most useful when working with Objective-C libraries from Swift, obviously.