源代码:
//程序目的:学习《从零开始学swift》
//第20章:错误处理
//Create By ChenZhen
enum DAOError: Error {
case Nodata
case PrimaryKeyNull
}
class Note {
var date: NSDate?
var content: String?
init(date: NSDate?, content: String?) {
self.date = date
self.content = content
}
}
class NoteDAO {
//保存数据列表
private var listData = [Note]()
//插入Note方法
func create(model: Note) {
listData.append(model)
}
//删除Note方法
func remove(model: Note) throws {
guard let date = model.date else {
//抛出“主键为空”错误
throw DAOError.PrimaryKeyNull
}
//比较日期主键是否相等
for (index, note) in listData.enumerated() where note.date == date {
listData.remove(at: index)
}
}
//修改Note方法
func modify(model: Note) throws {
guard let date = model.date else {
//抛出主键为空的错误
throw DAOError.PrimaryKeyNull
}
//比较日期主键是否相等
for note in listData where note.date == date {
note.content = model.content
}
}
//查询所有数据的方法
func findAll() throws -> [Note] {
guard listData.count > 0 else {
//抛出“没有数据”错误
throw DAOError.Nodata
}
defer {
print("关闭数据库")
}
defer {
print("释放语句对象")
}
return listData
}
//修改Note方法
func findBy(model: Note) throws -> Note? {
guard let date = model.date else {
//抛出主键为空的错误
throw DAOError.PrimaryKeyNull
}
//比较日期主键是否相等
for note in listData where note.date == date {
return note
}
return nil
}
}
//测试示例
//日期格式对象
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dao = NoteDAO()
//查询所有数据
do {
try dao.findAll()
} catch DAOError.Nodata {
print("没有数据")
//准备要插入的数据
var date1: NSDate = dateFormatter.date(from: "2016-01-01 16:01:03")! as NSDate
var note1: Note = Note(date: date1, content: "welcome to mynote.")
var date2: NSDate = dateFormatter.date(from: "2016-01-02 8:01:03")! as NSDate
var note2: Note = Note(date: date2, content: "欢迎使用mynote。")
//插入数据
dao.create(model: note1)
dao.create(model: note2)
}
do {
var note: Note = Note(date: nil, content: "welcome to mynote")
try dao.remove(model: note)
} catch DAOError.PrimaryKeyNull {
print("主键为空。")
}
func printNotes() throws {
let datas = try dao.findAll()
for note in datas {
print("date: \(note.date!) - content: \(note.content!)")
}
}
try printNotes()