Ios 如何使用swift3将已排序的结构放入另一个结构/字典?

Ios 如何使用swift3将已排序的结构放入另一个结构/字典?,ios,swift3,Ios,Swift3,我试图在我的TableView中创建字母部分,到目前为止,我已经设法将我的数据库放入struct,从数据库中获取每个名称的首字母,并根据部分标题对其进行排序。 我的问题是,我没有将排序后的变量放入另一个结构并在表中显示它 我的结构: struct CrimesInfo { let name: String let detail: String let time: String init(name:String, detail: String, time: S

我试图在我的TableView中创建字母部分,到目前为止,我已经设法将我的数据库放入struct,从数据库中获取每个名称的首字母,并根据部分标题对其进行排序。 我的问题是,我没有将排序后的变量放入另一个结构并在表中显示它

我的结构:

struct CrimesInfo {

    let name: String
    let detail: String
    let time: String


    init(name:String, detail: String, time: String) {
        self.name = name
        self.detail = detail
        self.time = time
    }

    init(fromResultSet: FMResultSet) {
        self.init(
            name: fromResultSet.string(forColumn: "Name"),
            detail: fromResultSet.string(forColumn: "Detail"),
            time: fromResultSet.string(forColumn: "Time")
        )

    }
}

struct CrimeNameSection {

    var firstLetter: Character
    var crimes: [CrimesInfo]

    init(title: Character, objects: [CrimesInfo]) {
        firstLetter = title
        crimes = objects
    }
}
我的数据库存储在结构“CrimesInfo”中,排序后我想将其插入结构“CrimeNameSection”(标题:名称的第一个字母,对象:相应的其余数据)

我的代码:

class SectionData {

    var crimeInfo : [CrimesInfo] = []

    func getCrimesData() {
        crimeInfo = ModelManager.getInstance().getAllCrimeInfo() // get the database into the struct
    }

    func getSectionFromData() -> [CrimeNameSection] { // get the fisrt letter of 'name', sort it and get in the another struct
        var crimeIndex = [Character: [CrimesInfo]]()
        var CrimeSections = [CrimeNameSection]()
        for crime in crimeInfo {
            if let firstCharacter = crime.name.characters.first {
                if crimeIndex[firstCharacter] == nil {
                    crimeIndex[firstCharacter] = [crime]
                } else {
                    crimeIndex[firstCharacter]?.append(crime)
            }
        }
    }

    let sortedIndex = crimeIndex.sorted { $0.0 < $1.0 } // type: [(key: Character, value:[CrimesInfo])]

    for key in sortedIndex { // get the sorted data into struct 'CrimeNameSection'
        let sortedSections = CrimeNameSection(title: sortedIndex(key), objects: sortedIndex(value)) // error: 'Use of unresolved identifier 'value'
    }

    CrimeSections.append(sortedSections)

    return CrimeSections
    }
}
类节数据{
var crimeInfo:[CrimesInfo]=[]
func getCrimesData(){
crimeInfo=ModelManager.getInstance().getAllCrimeInfo()//将数据库放入结构中
}
func getSectionFromData()->[CrimeNameSection]{//获取“name”的第一个字母,对其排序,然后进入另一个结构
var crimeIndex=[字符:[CrimesInfo]]()
var CrimeSections=[crimenaesection]()
《犯罪信息》中的犯罪{
如果让firstCharacter=crime.name.characters.first{
如果犯罪索引[firstCharacter]==nil{
犯罪索引[第一个字符]=[犯罪]
}否则{
犯罪索引[第一个字符]?.附加(犯罪)
}
}
}
让sortedIndex=crimeIndex.sorted{$0.0<$1.0}//类型:[(键:字符,值:[CrimesInfo])]
对于sortedIndex{//中的键,将排序后的数据放入结构“CrimeNameSection”
让sortedSections=CrimeNameSection(标题:sortedIndex(键),对象:sortedIndex(值))//错误:“使用未解析标识符”值
}
CrimeSections.append(已分类分区)
返回犯罪记录
}
}

给出了一个犯罪信息列表

let crimes = [
    CrimesInfo(name: "ba", detail: "", time: ""),
    CrimesInfo(name: "aa", detail: "", time: ""),
    CrimesInfo(name: "ab", detail: "", time: ""),
    CrimesInfo(name: "ca", detail: "", time: ""),
    CrimesInfo(name: "ac", detail: "", time: ""),
    CrimesInfo(name: "bb", detail: "", time: ""),
]
你可以写

let sections: [CrimeNameSection] = crimes
    .sorted { $0.name < $1.name }
    .reduce([CrimeNameSection]()) { result, crime -> [CrimeNameSection] in
        let crimeFirstLetter = crime.name.characters.first ?? " "

        guard var index = result.index(where: { $0.firstLetter == crimeFirstLetter }) else {
            let newSection = CrimeNameSection(title: crimeFirstLetter, objects: [crime])
            return result + [newSection]
        }

        var result = result
        var section = result[index]
        section.crimes.append(crime)
        result[index] = section
        return result
    }
CrimeNameSection(firstLetter: "a", crimes: crimes)
只是一张纸条 让我们看看您的
CrimeNameSection

struct CrimeNameSection {

    var firstLetter: Character
    var crimes: [CrimesInfo]

    init(title: Character, objects: [CrimesInfo]) {
        firstLetter = title
        crimes = objects
    }
}
您命名了初始值设定项
对象
的第二个参数。这在语义上是错误的,因为CrimeInfo不是一个对象,而是一个值

为什么不简单地删除初始值设定项和结构以公开memberwise初始值设定项?看

struct CrimeNameSection {
    var firstLetter: Character
    var crimes: [CrimesInfo]
}
现在你可以写作了

let sections: [CrimeNameSection] = crimes
    .sorted { $0.name < $1.name }
    .reduce([CrimeNameSection]()) { result, crime -> [CrimeNameSection] in
        let crimeFirstLetter = crime.name.characters.first ?? " "

        guard var index = result.index(where: { $0.firstLetter == crimeFirstLetter }) else {
            let newSection = CrimeNameSection(title: crimeFirstLetter, objects: [crime])
            return result + [newSection]
        }

        var result = result
        var section = result[index]
        section.crimes.append(crime)
        result[index] = section
        return result
    }
CrimeNameSection(firstLetter: "a", crimes: crimes)
更新 这就是填充表视图的方式

class Table: UITableViewController {

    var sections: [CrimeNameSection] = ...

    override func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].crimes.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let crime: CrimesInfo = sections[indexPath.section].crimes[indexPath.row]

        // TODO: use crime to populate your cell
    }

}

给出了一个列表
CrimeInfo

let crimes = [
    CrimesInfo(name: "ba", detail: "", time: ""),
    CrimesInfo(name: "aa", detail: "", time: ""),
    CrimesInfo(name: "ab", detail: "", time: ""),
    CrimesInfo(name: "ca", detail: "", time: ""),
    CrimesInfo(name: "ac", detail: "", time: ""),
    CrimesInfo(name: "bb", detail: "", time: ""),
]
你可以写

let sections: [CrimeNameSection] = crimes
    .sorted { $0.name < $1.name }
    .reduce([CrimeNameSection]()) { result, crime -> [CrimeNameSection] in
        let crimeFirstLetter = crime.name.characters.first ?? " "

        guard var index = result.index(where: { $0.firstLetter == crimeFirstLetter }) else {
            let newSection = CrimeNameSection(title: crimeFirstLetter, objects: [crime])
            return result + [newSection]
        }

        var result = result
        var section = result[index]
        section.crimes.append(crime)
        result[index] = section
        return result
    }
CrimeNameSection(firstLetter: "a", crimes: crimes)
只是一张纸条 让我们看看您的
CrimeNameSection

struct CrimeNameSection {

    var firstLetter: Character
    var crimes: [CrimesInfo]

    init(title: Character, objects: [CrimesInfo]) {
        firstLetter = title
        crimes = objects
    }
}
您命名了初始值设定项
对象
的第二个参数。这在语义上是错误的,因为CrimeInfo不是一个对象,而是一个值

为什么不简单地删除初始值设定项和结构以公开memberwise初始值设定项?看

struct CrimeNameSection {
    var firstLetter: Character
    var crimes: [CrimesInfo]
}
现在你可以写作了

let sections: [CrimeNameSection] = crimes
    .sorted { $0.name < $1.name }
    .reduce([CrimeNameSection]()) { result, crime -> [CrimeNameSection] in
        let crimeFirstLetter = crime.name.characters.first ?? " "

        guard var index = result.index(where: { $0.firstLetter == crimeFirstLetter }) else {
            let newSection = CrimeNameSection(title: crimeFirstLetter, objects: [crime])
            return result + [newSection]
        }

        var result = result
        var section = result[index]
        section.crimes.append(crime)
        result[index] = section
        return result
    }
CrimeNameSection(firstLetter: "a", crimes: crimes)
更新 这就是填充表视图的方式

class Table: UITableViewController {

    var sections: [CrimeNameSection] = ...

    override func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].crimes.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let crime: CrimesInfo = sections[indexPath.section].crimes[indexPath.row]

        // TODO: use crime to populate your cell
    }

}

我建议反对
crimenasection
。只需使用从
字符
[CrimeInfo]
的字典即可。这样会更容易合作

extension Array {
    func groupBy<Key>(_ keyGenerator: (Element) -> Key)
        -> [Key: [Element]] {
        var result = [Key: [Element]]()

        for element in self {
            let key = keyGenerator(element)
            var array = result[key] ?? []
            array.append(element)
            result[key] = array
        }

        return result
    }
}

let crimes = [
    CrimesInfo(name: "ba", detail: "", time: ""),
    CrimesInfo(name: "aa", detail: "", time: ""),
    CrimesInfo(name: "ab", detail: "", time: ""),
    CrimesInfo(name: "ca", detail: "", time: ""),
    CrimesInfo(name: "ac", detail: "", time: ""),
    CrimesInfo(name: "bb", detail: "", time: ""),
]

let crimesByInitial = crimes.groupBy{ $0.name.characters.first! }

我建议反对
crimenasection
。只需使用从
字符
[CrimeInfo]
的字典即可。这样会更容易合作

extension Array {
    func groupBy<Key>(_ keyGenerator: (Element) -> Key)
        -> [Key: [Element]] {
        var result = [Key: [Element]]()

        for element in self {
            let key = keyGenerator(element)
            var array = result[key] ?? []
            array.append(element)
            result[key] = array
        }

        return result
    }
}

let crimes = [
    CrimesInfo(name: "ba", detail: "", time: ""),
    CrimesInfo(name: "aa", detail: "", time: ""),
    CrimesInfo(name: "ab", detail: "", time: ""),
    CrimesInfo(name: "ca", detail: "", time: ""),
    CrimesInfo(name: "ac", detail: "", time: ""),
    CrimesInfo(name: "bb", detail: "", time: ""),
]

let crimesByInitial = crimes.groupBy{ $0.name.characters.first! }


为什么你讨厌缩进?哈哈。我不讨厌缩进,我总是在我的代码中使用缩进,但当我发布这个问题时,一切都变得一团糟,所以我就这样离开了。谢谢你的观察。你能修复它吗?你需要什么
crimenaesection
?为什么不把字典从
字符
保存到
[CrimeInfo]
?修复了它。我认为您使用字典而不是第二个结构是正确的,但是我想在tableView中显示数据,并且对我来说使用结构更容易。你能告诉我你会怎么做吗?你为什么讨厌缩进?哈哈。我不讨厌缩进,我总是在我的代码中使用它,但当我发布这个问题时,一切都变得一团糟,所以我就这样离开了。谢谢你的观察。你能修复它吗?你需要什么
crimenaesection
?为什么不把字典从
字符
保存到
[CrimeInfo]
?修复了它。我认为您使用字典而不是第二个结构是正确的,但是我想在tableView中显示数据,并且对我来说使用结构更容易。你能告诉我你会怎么做吗?非常感谢。。。。它起作用了,我按照你在便条中指出的那样修改了结构。我还有一个问题:如何访问第二个结构?我想在TableView中显示数据,我是说在override func TableView cellForRowAt indexPath中?谢谢,运行顺利,代码看起来真的很美观,再次感谢。。。这对我帮助很大,非常感谢你。。。。它起作用了,我按照你在便条中指出的那样修改了结构。我还有一个问题:如何访问第二个结构?我想在TableView中显示数据,我是说在override func TableView cellForRowAt indexPath中?谢谢,运行顺利,代码看起来真的很美观,再次感谢。。。它帮助我成为了一个
UITableViewDataSource
,您需要按索引检索节。使用字典,您必须对每个
numberofrowsinssection
cellForRowAt
调用上的键进行排序,才能找到引用的节。节数组更适合。@Jimmatt您是否介意建议进行编辑,如果您认为合适的话?您的代码看起来适合生成词典,但似乎与
UITableViewDataSource
不匹配。上面@appzYourLife给出的答案显示了数组作为
UITableViewDataSource
的数据结构有多好。要充当
UITableViewDataSource
,需要按索引检索节。使用字典,您必须对每个
numberofrowsinssection
cellForRowAt
调用上的键进行排序,才能找到引用的节。节数组更适合。@Jimmatt您是否介意建议进行编辑,如果您认为合适的话?您的代码看起来适合生成词典,但似乎与
UITableViewDataSource
不匹配。答案是