2016-02-12 54 views
1

我想根據用戶輸入在swift中創建動態結構。在Swift中動態結構創建 - 基於用戶輸入

struct Diagnosis { 

var diagName = String() // Name of the diagnosis 
var diagSymptoms = [String]() // Symptoms of the diagnosis in a ranked array to identify prevelancy 
var diagSpecialization = [String]() // the specializations which would mostly encounter this diagnosis 
var diagRank = Int() // the overall rank of the diagnosis 
var diagSynonoms = [String]() // the other name thru which the same diagnosis is called/referred. 

// func init(diagName: String(),diagSymptoms: [String](),diagSpecialization: [String](),diagSynonoms: [String]()) 
init(let pasdiagName: String,let pasdiagSymptoms:Array<String>) { 
    self.diagName = pasdiagName 
    self.diagSymptoms = pasdiagSymptoms 
} 
} 

var maleria = Diagnosis(pasdiagName: "Maleria",pasdiagSymptoms: ["fever","chill","body pain"]) 

上面創建結構maleria - 但在未來,我希望能有來自用戶的輸入,併爲輸入字符串

var abc = "typhoid" 

let valueof(abc) = Diagnosis() 
創建一個結構

的功能價值是我只是把這裏任意地使我的解釋清楚。 我知道我可以在Python中做到這一點,我是新來的迅速。先謝謝您的幫助。

+0

你描述的被稱爲字典... – Wain

回答

0

由於@When建議您應該使用Dictionary

這是如何創建一個可變字典,其中密鑰是String,值可以是任何類型。

var dict = [String:Any]() 

這是你如何把鍵/值對到字典

dict["year"] = 2016 
dict["word"] = "hello" 
dict["words"] = ["hello", "world"] 

這就是你如何提取值,並用它

if let word = dict["word"] as? String { 
    print(word) // prints "hello" 
} 
+0

非常感謝 - 它應該工作(對我來說,我很恥辱,我忽略了這個:() – swami