> On 29 Dec 2015, at 10:54 AM, Philippe Hausler <phaus...@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:

https://github.com/lhoward/swift-corelibs-foundation/blob/lhoward/nscoding/Foundation/NSSpecialValue.swift

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.

e.g.

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 {
            aCoder.encodePoint(self)
        }
    }
    
    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
_______________________________________________
swift-corelibs-dev mailing list
swift-corelibs-dev@swift.org
https://lists.swift.org/mailman/listinfo/swift-corelibs-dev

Reply via email to