Swift中的动态结构创建 - 基于用户输入

时间:2016-02-12 06:47:54

标签: swift struct

我正在尝试根据用户输入在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中做到这一点,我是swift的新手。在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

建议 @Wain ,您应该使用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"
}
相关问题