swiftlistrealmnscopying

Can't make realm List<T> conform NSCopying


I am trying to make List< T > conform NSCopying. I can't because:

  1. @objc is not supported within extensions of generic classes.
  2. I can't inherit List as it is a final class.
  3. If I implement "public func copy(with zone: NSZone? = nil) -> Any" without marking conform NSCopying. I just get error:"...copyWithZone:]: unrecognized selector sent to instance"

So although there is copy() in List< T >, we can never really use it.

Current I have to make copy outside of List< T >, using iteration. I can't simply using instanceOfList.copy().


Solution

  • It's not necessary to make List<T> conform to NSCopying in order to extend it with a copy member function unless you're trying to copy it within a generic context from Objective-C. NSCopying is a legacy protocol that does not make a lot of sense to use in pure Swift. It is class-bound and does not have a very nice type signature.

    If you're trying to use NSCopying in a generic context in pure Swift, consider defining your own Copyable protocol and extending types to conform to that. Since it isn't @objc, you should be fine. Existing types that already conform to NSCopying will require extensions to also conform to Copyable, but you can put the logic in an extension of NSCopying.

    import Foundation
    
    protocol Copyable {
        mutating func copy() -> Self
    }
    
    extension NSCopying {
        func copy() -> Self {
            return copy(with: nil) as! Self
        }
    }
    
    extension MyTypeThatConformsToNSCopying: Copyable { }
    

    Now, I'm a little curious why you might be trying to conform List<T> to NSCopying. Are you looking for an unmanaged copy of the list? You could just use Array(myList) to get an Array from a List.