斯威夫特 - 创建自定义类类型的`Array` [英] Swift - create custom class of type `Array`

查看:144
本文介绍了斯威夫特 - 创建自定义类类型的`Array`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能创建一个快捷自定义类,类型为阵列的?
准确的说,我有一个自定义的类类型的,现在我想创建一个单就是汽车的数组秒。 (因为我希望能够从任何地方访问它在我的应用程序)。

我的解决方法是定义我的单身为的NSMutableArray 。但我看到了导致我的code我的一些问题。所以,我希望将它定义为迅速数组。
我该怎么办呢?

我的code现在是:

 类MyCars:NSMutableArray里{
    类VAR sharedInstance:MyCars {
        结构静态{
            静止无功实例:MyCars?
            静止无功令牌:dispatch_once_t = 0
        }        dispatch_once(安培; Static.token){
            Static.instance = MyCars()
        }        返回Static.instance!
    }
}


解决方案

要创建租车的单阵列你不需要创建一个新类 - 只是一个结构用一个静态成员:

 结构MyCars {
    静止无功sharedInstance =阵列<汽车>()
}

请注意, sharedInstance 初始化一次 - 阅读这个答案了解更多信息。

附录

如果你想使用 MyCars 引用的数组,你可以定义一个typealias并使用不同的名称包含单,如结构:

  typealias MyCars =阵列<汽车>结构辛格尔顿{
    静止无功myCars = MyCars()
}

How can I create a custom class in swift that is of type Array? To be exact, I have a custom class of type Car, and now I want to create a singleton that is an array of Cars. (Because I want to be able to access it from anywhere in my app).

My workaround is to define my singleton as NSMutableArray. But I see that causes my some problems in my code. So I wish to define it as swift array. How can I do it?

My code now is:

class MyCars: NSMutableArray {
    class var sharedInstance: MyCars {
        struct Static {
            static var instance: MyCars?
            static var token: dispatch_once_t = 0
        }

        dispatch_once(&Static.token) {
            Static.instance = MyCars()
        }

        return Static.instance!
    }
}

解决方案

To create a singleton array of Car you don't need to create a new class - just a struct with a static member:

struct MyCars {
    static var sharedInstance = Array<Car>()
}

Note that the sharedInstance is initialized once - read this answer for more info

Addendum

In case you want to use MyCars to refer to an array of Car, you can just define a typealias and use a different name for the struct containing the singleton, such as:

typealias MyCars = Array<Car>

struct Singleton {
    static var myCars = MyCars()
}

这篇关于斯威夫特 - 创建自定义类类型的`Array`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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