swift - immutable of type only has mutating members -
following code throwing error "immutable value of type [user] has mutating members named append" please advise.
library or framework code (precompiled)
class database { var data: any? //can change code has generic placeholder init(data: any?=nil) { self.data = data } }
users of library or framework code
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 problem persists (self.data as! [user]).append(item) //error } }
attempt 1, seems working still wonder why above code doesn't work.
func additem(item: user) { var users = self.data as! [user] users.append(item); self.data = users; }
don't re-assignment, how can in place mutability possible
i've written (what believe be) elegant solution problem.
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 { { return accessor.getter(rawvalue.memory) } set { rawvalue.memory = accessor.setter(newvalue) } } }
which allows for:
mediator<any?, [user]>(&self.data).value.append(item)
Comments
Post a Comment