Subclassing NSString in Swift?

I am creating an NSTextStorage implementation backed by my tree-shaped
Swift data structure, class Rope.

The subclassing instructions for NSTextStorage tell me to override
methods attributes(at:effectiveRange:), replaceCharacters(in:with:), and
setAttributes(_:range:), plus the string property.

Implementing the string property by flattening my data structure
into a String will be very slow. Looks like the thing to do is
return a custom subclass of NSString that implements at least
method character(at:) and property length. E.g.,

class RopeString : NSString {
	let rope: Rope<Substring>
        init(rope r: Rope<Substring>) {
		rope = r
	}
        
        required init?(coder: NSCoder) {
                fatalError("init(coder:) has not been implemented")
        }
        
        required init?(pasteboardPropertyList propertyList: Any, ofType type: NSPasteboard.PasteboardType) {
                fatalError("init(pasteboardPropertyList:ofType:) has not been implemented")
        }
        
        public override var length: Int {
		return 0
	}
	override func character(at index: Int) -> unichar {
		return 0
	}
}

Xcode gripes about my stubbed-out implementation,

Rope.swift:1083:1: 'required' initializer 'init(stringLiteral:)' must be provided by subclass of 'NSString'

If I accept Xcode's suggested "Fix," it inserts this method,

        required convenience init(stringLiteral value: StaticString) {
                fatalError("init(stringLiteral:) has not been implemented")
        }

and it gripes about the method it just inserted,

Rope.swift:1084:30: Overriding declarations in extensions is not supported
``

I don't know what to do about that.

Is it possible to subclass NSString in Swift, or am I barking up the
wrong tree?

Dave

Nevermind, the problem (and a fix that seems to work for me) are
described in problem report,

Sometimes it pays to use Google instead of DuckDuckGo; the former seems
to have an index of the Swift bug database, but the latter does not.

Dave

2 Likes