在Swift中,像String
NSCoder
方法一样,encodeObject(_:forKey:)
结构也被视为类对象。我确实知道String
直接与Objective-C类NSString
桥接,但是有没有办法使自定义struct
表现类似?也许将其桥接到自定义类?我希望能够做这样的事情:
struct SortedArray <Value: Comparable> {}
// Would I need to create a bridge between
// SortedArray and NSSortedArray? Can I even do that?
class NSSortedArray <Value: Comparable> : NSObject, NSCoding {
required init?(coder aDecoder: NSCoder) {}
func encodeWithCoder(aCoder: NSCoder) {}
}
class MyClass : NSObject, NSCoding {
private var objects: SortedArray<String> = SortedArray<String>()
required init?(coder aDecoder: NSCoder) {
guard let objects = aDecoder.decodeObjectForKey("objects") as? SortedArray<String> else { return nil }
self.objects = objects
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(objects, forKey: "objects")
}
}
最佳答案
目前尚无法实现。 SE-0058将解决该问题,但不推荐使用Swift3。SE-0058的最终实现将有望不仅处理ObjC桥接;例如,在更通用的解决方案中也允许C++或.NET桥接。