【问题标题】:Referring to an object using a string variable's value in Swift在 Swift 中使用字符串变量的值引用对象
【发布时间】:2017-05-27 18:03:10
【问题描述】:

在下面的代码中,我无法使用 performActivity 方法来增加角色的幸福感。因为 'need' 以字符串的形式出现,其值为“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)

【问题讨论】:

    标签: swift methods swift3 ios10


    【解决方案1】:

    这种设计在某些方面是倒退的。让每个需要一个对象,并让每个活动直接修改它。这里不需要(或渴望)字符串。如果您将效果存储为DictionaryLiteral 而不是Dictionary,那么使用它也会更容易一些。这样我们就不需要费力地将需求设为 Hashable。

    // 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
    }
    

    【讨论】:

    • 非常感谢罗伯!这是一个完美的解决方案。
    猜你喜欢
    • 2012-05-22
    • 1970-01-01
    • 2017-11-16
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    • 2013-10-08
    相关资源
    最近更新 更多