[英]Dynamic Struct creation in Swift - based on user input
I am trying to create dynamic struct in swift based on user input. 我试图根据用户输入快速创建动态结构。
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"])
The above creates the structure maleria - But in future I want to have the input from user and create a structure for that inputted string 上面的代码创建了maleria结构-但是将来我想从用户那里获取输入,并为输入的字符串创建一个结构
var abc = "typhoid"
let valueof(abc) = Diagnosis()
The value of function is something I just put here arbitrarily to make my explanation clear. 为了使我的解释清楚,我只是在这里随意介绍了函数的价值。 I know I could do this in python and I am new to swift.
我知道我可以用python做到这一点,而我是新手。 Thanks in advance for the help.
先谢谢您的帮助。
As @Wain suggested, you should use a Dictionary
. 正如@Wain建议的那样,您应该使用
Dictionary
。
This is how you create a mutable dictionary where the key is a String
and the value can be any type. 这是创建可变字典的方法,其中键是
String
,值可以是任何类型。
var dict = [String:Any]()
This is how you put key/value pairs into the dictionary 这是将键/值对放入字典中的方式
dict["year"] = 2016
dict["word"] = "hello"
dict["words"] = ["hello", "world"]
And this is how you extract a value and use it 这就是您提取值并使用它的方式
if let word = dict["word"] as? String {
print(word) // prints "hello"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.