不可变的类型只有变异成员

时间:2015-04-25 22:04:37

标签: swift

以下代码抛出错误"类型[User]的不可变值仅包含名为append"的变异成员。请指教。

库或框架代码(预编译)

class Database {
    var data: Any? //can change this code but has to be a generic placeholder

    init(data: Any?=nil) {
        self.data = data
    }
}

图书馆或框架代码的用户

class User {
    var first: String
    var last: String

    init(first: String, last:String) {
        self.first = first
        self.last = last
    }
}

class Test: Database {

    init() {
        super.init(data: [User]())
    }

    func addItem(item: User) { //edit User type from Any but problem persists
        (self.data as! [User]).append(item) //error
    }
}

尝试1 ,这似乎有效,但仍然想知道为什么上面的代码无效。

func addItem(item: User) {
    var users = self.data as! [User]
    users.append(item);
    self.data = users; 
} 

不喜欢重新分配,如何实现可变性

1 个答案:

答案 0 :(得分:1)

我为这个问题编写了一个(我相信的)优雅解决方案。

public struct Accessor<T, U>
{
    public let (getter: (T -> U), setter: (U -> T))

    public init()
    {
        (getter, setter) = ({ $0 as! U }, { $0 as! T })
    }

    public init(_ getter: (T -> U), _ setter: (U -> T))
    {
        self.getter = getter
        self.setter = setter
    }
}

extension Accessor: NilLiteralConvertible
{
    public init(nilLiteral: ())
    {
        self.init()
    }
}

public class Mediator<T, U>
{
    public var rawValue: UnsafeMutablePointer<T>
    public var accessor: Accessor<T, U>

    public init(_ rawValue: UnsafeMutablePointer<T>, _ accessor: Accessor<T, U> = nil)
    {
        self.rawValue = rawValue
        self.accessor = Accessor<T, U>({ $0 as! U }, { $0 as! T })
    }

    public var value: U
    {
        get
        {
            return accessor.getter(rawValue.memory)
        }

        set
        {
            rawValue.memory = accessor.setter(newValue)
        }
    }
}

允许:

Mediator<Any?, [User]>(&self.data).value.append(item)