简体   繁体   English

从 objc 改变 swift 数组?

[英]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.我想从 objc 添加到数组变量。

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

myArray is typed as NSArray not NSMutableArray, so has no method addObject. myArray 的类型为 NSArray 而不是 NSMutableArray,因此没有方法 addObject。

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根据得墨忒耳定律,这是更好的编写方式,因为您没有访问foo属性上的方法

You may try this as well:你也可以试试这个:

@objc class Foo: NSObject {
    var myArray = NSMutableArray()
}

And then from Objective-C:然后从Objective-C:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM