Bright Future Bright Future - 2 months ago 7
Swift Question

How to get a type property through a matching property of it?

I have this class:

class AClass {
var name = "Name"
var value = 0

static var A = AClass(name: "A", value: 1)
static var B = AClass(name: "B", value: 2)
}


I have a function that returns the name of
A
and
B
, how do I get
A
and
B
as
AClass
instances WITH string
A
and
B
, like this?

func someMethod(name: String) -> AClass
// func("A") will return A: AClass


UPDATE:

I have many type properties in my actual project, so I'm looking for a convenient way to get 'em all without having to create a value of each type property.

Answer

I guess this is what you are looking for

class AClass {
 var name = "Name"
 var value = 0

 static var dataDict = [String: AClass]()

 init(name: String) {
  self.name = name
 }


static func someMethod(name: String) -> AClass {
 if let obj = AClass.dataDict[name] {
  return obj
} else {
  AClass.dataDict[name] = AClass(name: name)
  return AClass.dataDict[name]!
}

}

}

Get object of AClass like:

let obj = AClass.someMethod(stringReturnValue) // AClass.someMethod("A") 

// here if already AClass object exist with this key in AClass.dataDict then it will return that object else created one and store it in dataDict.

Comments