ios - Is there any way of sharing getter and setter through properties in Swift? -
i'm building helper enable typed access nsuserdefaults
properties. this:
struct userdefaults { private static var standarduserdefaults: nsuserdefaults = { return nsuserdefaults.standarduserdefaults() }() private static let propkey = "prop" static var prop: bool { { return standarduserdefaults.boolforkey(propkey) } set { standarduserdefaults.setbool(newvalue, forkey: propkey) standarduserdefaults.synchronize() } } }
this way can have nice syntax reading , writing nsuserdefaults
:
userdefaults.prop // read userdefaults.prop = false // write
the problem there's lot of boilerplate code this, need 10 lines each aditional property.
is there way of reducing amount of lines needed each new property? reusing getter , setter? kind of run time generator?
you can try wrapping actual value in class handles dirty work you:
class wrappeduserdefault<t> { let key : string let defaultvalue : t var value : t { { if let value = userdefaults.standarduserdefaults.objectforkey(key) as? t { return value } else { return defaultvalue } } set { if let value = newvalue as? anyobject { userdefaults.standarduserdefaults.setvalue(value, forkey: key) } else { userdefaults.standarduserdefaults.removeobjectforkey(key) } userdefaults.standarduserdefaults.synchronize() } } init(key:string, defaultvalue:t) { self.key = key self.defaultvalue = defaultvalue } } struct userdefaults { static let standarduserdefaults = nsuserdefaults.standarduserdefaults() static let ready = wrappeduserdefault<bool>(key:"ready", defaultvalue: true) static let count = wrappeduserdefault<int>(key: "count", defaultvalue: 0) }
then little bit more code wind with:
userdefaults.count.value++ userdefaults.ready.value = true userdefaults.ready.value
if verbosity of ready.value
bothers you, can hide that, although you're you're having fair amount of copy/paste code:
struct userdefaults { static let standarduserdefaults = nsuserdefaults.standarduserdefaults() private static let readywrapper = wrappeduserdefault<bool>(key:"ready", defaultvalue: true) static var ready : bool { { return readywrapper.value } set { readywrapper.value = newvalue } } }
at least in case though, copy/paste code trivial, unlikely need altered in future.
Comments
Post a Comment