2017-05-27 69 views
0

在我的代碼中,我無法獲得performActivity方法來增加角色幸福感。因爲「需要」是帶有「幸福」價值的字符串,而我需要改變作爲類實例的「幸福」。我會很感激任何幫助!引用Swift中使用字符串變量值的對象

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

回答

2

這種設計有幾種方式倒退。使每個需求成爲一個對象,並讓每個活動直接修改它。這裏沒有必要(或者期望)字符串。如果您將效果存儲爲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 
} 
+0

非常感謝你Rob!這是一個完美的解決方案。 –