如何一个计算属性添加到阵列< T&GT ;? [英] How to add a computed property to Array<T>?

查看:173
本文介绍了如何一个计算属性添加到阵列< T&GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var _feedbacks: [feedBack]!

我想补充一个属性设置为[反馈]这样我就可以说:

var _ID = _feedBacks.ID 

我想:

extension Array {   
    var ID: String {        
        get { 
            return self.ID
        }

        set {
            self.ID = newValue
        }
    }
}

不过,编译器会引发EXC_BAD_ACCESS当我尝试设置/获取 ID

import ObjectiveC

private var arrayAssocationKey: Void?

extension Array {
    var ID: String {
        get {
            return objc_getAssociatedObject(self, &arrayAssocationKey) as? String
        }
        set {
            objc_setAssociatedObject(self, &arrayAssocationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
        }
    }
}

但是,编译器调用错误`阵列不符合协议AnyObject

But the compiler calls the error `Array does not conform to protocol AnyObject

有任何解决方法来设置该属性?

Is there any workaround to set this property?

推荐答案

一直延伸阵列添加一个ID属性似乎有点小题大做。我想你会更好创建持有身份证件和反馈阵列,一类是这样的:

Extending all arrays to add an ID property seems like overkill. I think you'd be better off creating a class that holds an ID and an array of feedback, something like this:

    class feedbackCollection {
        var ID: String?
        var feedbacks: [feedback]?
    }

编辑:

在这个解决方案更通用的尝试可能对你有用:

A more generic attempt at this solution might be useful to you:

class IDArray<T> {
    var ID: String
    var items: [T]
    init(ID: String, items: [T]) {
        self.ID = ID
        self.items = items
    }
}

这将用于如下:

let ints = IDArray(ID: "1", items: [1, 2, 4])

let strings = IDArray(ID: "2", items: ["test", "this", "thing"])

strings.ID = "8"
strings.items.append("more")

这篇关于如何一个计算属性添加到阵列&LT; T&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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