【发布时间】:2015-02-27 03:41:46
【问题描述】:
我正在尝试在结构中创建一个变异函数,该函数将按其 String 属性对数组进行排序。这样,每当将一个项目添加到数组中时,它都会按字母顺序对其自身进行排序。我意识到我现在所拥有的试图在自己的数组的 didSet 方法中对数组进行更改,但我不确定现在该去哪里。目前我收到错误“线程 1:EXC_BAD_ACCESS (code=2, address=...)”。在尝试实现 sort 方法之前,所有其他代码都运行良好。
import Foundation
struct QuoteLibrary {
var title : String
var arrayOfSectionTitles: [String]
var arrayOfSections : [Section] = [] {
didSet {
self.configureSections()
}
}
mutating func configureSections() {
// Sort alphabetically
arrayOfSections.sort({ $0.title > $1.title })
let numberOfSections = arrayOfSections.count - 1
// Update the arrayOfSectionTitles whenever arrayOfSections is set
var titleArray: [String] = []
for k in 0...numberOfSections {
titleArray.append(arrayOfSections[k].title)
}
arrayOfSectionTitles = titleArray
// If a section has no quotes in it, it is removed
for j in 0...numberOfSections {
if arrayOfSections[j].arrayOfQuotes.count == 0 {
arrayOfSections.removeAtIndex(j)
return
}
}
}
}
struct Section {
var title : String, arrayOfQuotes:[Quote]
}
struct Quote {
var section : String, text : String
}
enum QuoteStatus: Int {
case Unchanged = 0
case Changed = 1
case Deleted = 2
case Added = 3
}
【问题讨论】:
标签: arrays sorting swift properties