[swift-corelibs-dev] NSCoding methods

Luke Howard lukeh at padl.com
Fri Jan 1 07:15:40 CST 2016

> On 29 Dec 2015, at 10:54 AM, Philippe Hausler <phausler at apple.com> wrote:
> It is ok on the special types; those are harder than they may seem… NSValue in Darwin has some limitations like that especially when it comes to secure coding or non standard aligned values.

I have a solution that’s not too inelegant, see:


This takes advantage of the fact that structures can implement protocols in Swift. NSRect, etc implement NSCoding (by way of NSSpecialValueCoding). The structures are then boxed by NSSpecialValue (a subclass of NSValue). It would have been nice to make NSSpecialValue a generic class but unfortunately it doesn’t appear you can specialise at runtime, which the unarchiver would need to do.


extension CGPoint: NSSpecialValueCoding {
    public init?(coder aDecoder: NSCoder) {
        if aDecoder.allowsKeyedCoding {
            self = aDecoder.decodePointForKey("NS.pointval")
        } else {
            self = aDecoder.decodePoint()
    public func encodeWithCoder(aCoder: NSCoder) {
        if aCoder.allowsKeyedCoding {
            aCoder.encodePoint(self, forKey: "NS.pointval")
        } else {
    public static func supportsSecureCoding() -> Bool {
        return true
    static func objCType() -> String {
        return "{CGPoint=dd}"

    func isEqual(aValue: Any) -> Bool {
        if let other = aValue as? CGPoint {
            return other == self
        } else {
            return false

There’s still NSConcreteValue for ObjC type representations but I found it difficult to merge the two (for reasons I can explain later).

Happy new year!

— Luke
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-corelibs-dev/attachments/20160102/7d63dcbc/attachment.html>

More information about the swift-corelibs-dev mailing list