Reputation: 6557
I am making my own class which stores information to do with a user. Just like the swiftyJSON framework, I would like to accsess the data as if the variable was a dictionary.
Example,
When using SwiftyJSON, you can run code as shown below:
let x = JSON["x"]
let y = JSON["y"].strVal
let x = JSON["z"].intVal
What I would loke to do is to have a class like the following below:
class User
{
private (set) public var DATA:[String:Any]
public init(){}
public function login(username:String, password:String)
{
//Login code here
self.DATA = loginResult
}
}
let user = User()
user.login(username:"username", password:"password")
let name = user["name"].strVal
How would I be able to write this in swift?
Upvotes: 0
Views: 36
Reputation: 8202
You want to use a subscript
:
class User
{
private (set) public var DATA:[String:Any]
public init(){}
public function login(username:String, password:String)
{
//Login code here
self.DATA = loginResult
}
subscript(key: String) -> Any? {
return DATA[key]
}
}
let user = User()
user.login(username:"username", password:"password")
let name = user["name"].strVal
You probably want to store DATA
as SwiftyJSON, so you can call strVal
, etc. on it - just update the backing property and subscript signature as needed.
Upvotes: 1