Swift 中的静态属性 [英] Static properties in Swift

查看:24
本文介绍了Swift 中的静态属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将以下 Objective-C 代码转换为 Swift.在我的 Objective-C 代码中,有一个静态变量,它是从一个类方法中访问的.

I'm trying to convert the following Objective-C code to Swift. In my Objective-C code, there's a static variable and its accessed from a class method.

@implementation SomeClass

static NSMutableArray *_items;

+ (void)someMethod {
    [_items removeAll];
}

@end

由于您无法从 Swift 中的类函数访问这样声明的类型 private var items = [AnyObject](),因此我为它创建了一个这样的存储属性.

Since you can't access types declared like this private var items = [AnyObject]() from class functions in Swift, I created a stored property for it like this.

class var items: [AnyObject] {
    return [AnyObject]()
}

我正在尝试从这样的类函数中调用一个方法.

And I'm trying to call a method on it from a class function like so.

class func someFunction() {
    items.removeAll(keepCapacity: false)
}

但我收到此错误[AnyObject]"类型的不可变值只有名为removeAll"的可变成员.

谁能告诉我这个错误的原因是什么以及如何纠正它?

Can anyone please tell me what's the cause of this error and how to correct it?

谢谢.

推荐答案

使用此代码:

class var items: [AnyObject] {
    return [AnyObject]()
}

你不是在创建一个存储属性——而是一个计算属性,最糟糕的是每次你访问它时,都会创建一个 [AnyObject] 的新实例,所以无论你添加到它,一旦它的引用超出范围,它就会丢失.

you are not creating a stored property - instead it's a computed property, and the worst part is that every time you access to it, a new instance of [AnyObject] is created, so whatever you add to it, it's lost as soon as its reference goes out of scope.

至于错误,静态计算属性返回您在其主体中创建的数组的不可变副本,因此您不能使用任何声明为 mutating - 和 的数组方法removeAll 就是其中之一.之所以不可变,是因为你定义了一个getter,而不是setter.

As for the error, the static computed property returns an immutable copy of the array that you create in its body, so you cannot use any of the array method declared as mutating - and removeAll is one of them. The reason why it is immutable is because you have defined a getter, but not a setter.

目前 Swift 类不支持静态属性,但结构支持 - 我经常使用的解决方法是定义一个内部结构:

Currently Swift classes don't support static properties, but structs do - the workaround I often use is to define an inner struct:

class SomeClass {
    struct Static {
        static var items = [AnyObject]()
    }
}

SomeClass.Static.items.append("test")

如果你想在每次引用 items 属性时摆脱 Static 结构,只需定义一个包装计算属性:

If you want to get rid of the Static struct every time you refer to the items property, just define a wrapper computed property:

class var items: [AnyObject] {
    get { return Static.items }
    set { Static.items = newValue }
}

以便可以更简单地访问该属性:

so that the property can be accessed more simply as:

SomeClass.items.append("test")

这篇关于Swift 中的静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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