我不是 Swift 专家,几个月来我一直在使用它来构建 Mac 应用程序。我想在内存中表示一个类似于 PHP 关联数组 但在 Swift 中的数据结构。假设我有一个数据表要加载到内存中,其中包含以下字段/记录:
ID Surname Name
1 XXX YYY
2 ZZZ WWW
3 JJJ KKK
我想要获得的是一个关联数组,就像我能够在 PHP 中获得的那样:
$arr[1]["Surname"] = "XXX"
$arr[1]["Name"] = "YYY"
$arr[2]["Surname"] = "ZZZ"
$arr[2]["Name"] = "WWW"
我只是无法在 Swift 中找到正确的数据结构来获得相同的结果。我尝试使用以下代码:
class resObject: NSObject {
private var cvs = [Int: [String: String]]()
override init() {
self.cvs[0] = ["Name" : "XXX"]
self.cvs[0] = ["Surname" : "YYY"]
self.cvs[1] = ["Name" : "ZZZ"]
self.cvs[1] = ["Surname" : "WWW"]
for (key, arr) in cvs {
let sur = arr["Surname"]
let nam = arr["Name"]
println("Row \(key) - Surname: \(sur), Name: \(nam)")
}
super.init()
}
}
在我看来它非常接近,但它不起作用。我在输出中得到的是以下内容(我不关心“可选”:
Row 0 - Surname: Optional("XXX"), Name: nil
Row 1 - Surname: Optional("ZZZ"), Name: nil
我尝试在调试中进行一些测试,我注意到保存在内存中的数据只是最后使用的键值对的数据(即,如果我首先分配姓氏,然后分配姓名,我得到的姓氏为 nil 和名称具有正确的值)。
请考虑一下,如示例所示,我在声明变量时不知道数据结构,因此我将其声明为空并稍后以编程方式填充它。
我不知道是我没有正确声明数据结构,还是 Swift 不允许这样做。任何帮助将不胜感激。
非常感谢。 问候, 阿莱西奥
最佳答案
一种方式是结构
的字典
。考虑:
struct Person {
var firstName: String
var lastName: String
}
var peopleByID = [ Int: Person ]()
peopleByID[1] = Person(firstName: "First", lastName: "Last")
peopleByID[27] = Person(firstName: "Another", lastName: "LastName")
var myID = 1 // Try changing this to 2 later
if let p = peopleByID[myID] {
println("Found: \(p.firstName) with ID: \(myID)")
}
else {
println("No one found with ID: \(myID)")
}
然后您可以更新结构:
peopleByID[1].firstName = "XXX"
peopleByID[27].lastName = "ZZZ"
你可以自由迭代:
for p in peopleByID.keys {
println("Key: \(p) value: \(peopleByID[p]!.firstName)")
}
请注意,仅仅是 [Person] 的数组并不是那么热门,因为 ID:
-- 可能不是 Int,但通常是 String
-- 即使它们仍然是 Int,数组占用的存储空间与编号最高的索引成比例,而 Dictionary 占用的存储空间仅与存储对象的数量成比例。想象一下只存储两个 ID:523123 和 2467411。
编辑
您似乎不提前知道将进入每个Person
对象的属性。这很奇怪,但你应该这样做:
struct Person {
var attributes = [String : String]() // A dictionary of String keys and String values
}
var peopleByID = [ Int : Person ]()
// and then:
var p1 = Person()
var p2 = Person()
p1.attributes["Surname"] = "Somename"
p1.attributes["Name"] = "Firstname"
p2.attributes["Address"] = "123 Main St."
peopleByID[1] = p1
peopleByID[2] = p2
if let person1 = peopleByID[1] {
println(person1.attributes["Surname"]!)
for attrKey in person1.attributes.keys {
println("Key: \(attrKey) value: \(person1.attributes[attrKey]!)")
}
}
关于arrays - Swift:具有多个键的关联数组:值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31736079/