从objc更改swift数组? [英] mutate swift array from objc?

查看:80
本文介绍了从objc更改swift数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下课程

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

我想从objc添加到数组变量.

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

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

myArray的输入类型为NSArray而不是NSMutableArray,因此没有方法addObject.

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

推荐答案

怎么样:

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

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

然后

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

根据《德米特尔法》 ,这是写它的更好方法,因为不要访问 foo

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

这篇关于从objc更改swift数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆