在我下面的代码中,我无法使用 performActivity 方法来增加角色的快乐度。因为“需要”作为一个字符串出现,值为“happiness”,而我需要对类实例“happiness”进行更改。如果有任何帮助,我将不胜感激!
// Character Needs Class
class CharNeeds {
var currentNeedValue : Int = 0
func changeNeedValue (changeBy : Int){
currentNeedValue += changeBy
}
}
// Activities Class
class Activities{
let activityName : String
var effects = [String: Int]()
//Initializers
init(activityName: String, effects: [String: Int]){
self.activityName = "Unnamed Activity"
self.effects = effects
}
//Methods
static func performActivity(activityName : Activities){
for (need, effect) in activityName.effects {
need.changeNeedValue(changeBy: effect)
}
}
}
//Testing
var happiness = CharNeeds()
var cycling = Activities(activityName: "cycling", effects: ["happiness":10])
Activities.performActivity(activityName: cycling)
最佳答案
这种设计在某些方面是倒退的。使每个需要一个对象,并让每个事件直接修改它。这里不需要(或不需要)字符串。如果将效果存储为 DictionaryLiteral
而不是 Dictionary
,使用它也会更容易一些。这样我们就不需要经历使需求可散列的麻烦。
// A need has an immutable name and a mutable value that can be increased and read
class Need {
let name: String
private(set) var value = 0
init(name: String) {
self.name = name
}
func increaseValue(by: Int){
value += by
}
}
// An Activity has an immutable name and an immutable list of needs and adjustments
class Activity {
let name: String
let effects: DictionaryLiteral<Need, Int>
init(name: String, effects: DictionaryLiteral<Need, Int>){
self.name = name
self.effects = effects
}
func perform() {
for (need, effect) in effects {
need.increaseValue(by: effect)
}
}
}
// Now we can assign happiness to this activity, and perform it.
let happiness = Need(name: "happiness")
let cycling = Activity(name: "cycling", effects: [happiness: 10])
cycling.perform()
happiness.value
如果您收到字符串,那么您只需要保留字符串到需求的映射。例如:
let needMap = ["happiness": Need(name: "happiness")]
if let happiness = needMap["happiness"] {
let cycling = Activity(name: "cycling", effects: [happiness: 10])
cycling.perform()
happiness.value
}
关于swift - 在 Swift 中使用字符串变量的值引用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44220103/