I'm trying to subclass NSMutableArray
in Swift to provide bridge functionality for a Swift array to some old Objective-C codebase. However, I can't find a functional example and all my attempts have failed so far. This is the closest I got to a functional example:
import UIKit
class MyArray: NSMutableArray {
var array: [Int]?
// Adding an initializer triggers the error: 'required' initializer 'init(arrayLiteral:)' must be provided by subclass of 'NSArray'
// override init() {
// self.array = []
// super.init()
// }
static func makeArray() -> MyArray {
let array = MyArray()
array.array = []
return array
}
override var count: Int {
get {
if let count = array?.count {
return count
}
return 0
}
}
override func insert(_ anObject: Any, at index: Int) {
print("insert called")
}
override func removeObject(at index: Int) {
print("removeObject called")
}
override func add(_ anObject: Any) {
print("Trying to add \(anObject)")
if let newInt = anObject as? Int {
array?.append(newInt)
}
}
override func removeLastObject() {
print("removeLastObject called")
}
override func replaceObject(at index: Int, with anObject: Any) {
print("replaceObject called")
}
}
func append42(array: NSMutableArray) {
array.add(42)
}
let myArray = MyArray.makeArray()
print("Before: \(myArray.array)")
myArray.array?.append(42)
// The following two lines generate a SIGABRT
//myArray.add(42)
//append42(array: myArray)
print("After: \(myArray.array)")
However, using the add
method always triggers a SIGABRT
. I'm using XCode 12.4 on Catalina.
EDIT (for clarifications): I know that Swift bridges Array
s to NSArray
s. However, I need to pass a reference to a Swift array to some Objective-C code accepting an NSMutableArray
and possibly making updates to the array.
Essentially I'm adding some Swift code to an existing project, and I'd like to use Swift typed arrays in the new code, but I still to pass these arrays to the old code. I know that I can make an NSMutableArray
copy of the Swift array, pass this copy to the old code, then copy it back to the Swift array but it's rather convoluted and hardly maintainable. What I'm tried to do is encapsulating a reference to a Swift array into an 'NSMutableArray' subclass so I can transparently use this subclass with the legacy code.