Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mutate swift array from objc?

Given the following class

@objc class Foo: NSObject {
  var myArray = [Bar]()
}

I'd like to add to array variable from objc.

Foo* foo = [[Foo alloc] init];
[foo.myArray addObject: bar];

myArray is typed as NSArray not NSMutableArray, so has no method addObject.

like image 495
eugene Avatar asked Dec 03 '25 02:12

eugene


1 Answers

How about:

@objc class Foo: NSObject {
  var myArray = [Bar]()

  func addBar(newBar: Bar) {
    myArray.append(newBar)
  }
}

then

Foo* foo = [[Foo alloc] init];
[foo addBar: bar];

According to the Law of Demeter this is the better way to write it, as you're not accessing a method on a property of foo

like image 87
Ashley Mills Avatar answered Dec 05 '25 14:12

Ashley Mills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!