funcattendLecture() throws { if sleptIn { throwCS193pError.missedLecture } askQuestions() // not done if you sleptIn because throw exits attendLecture() ... }
enumCS193pError: Error { case lateHomework(daysLate: Int) case missedLecture var localizedDescription: String { switchself { .. } } }
do { try somethingThatThrow() print("hello") // will only happen if somethingThatThrows() does not throw anything } catchCS193pError.lateHomework(let daysLate) {
} catchlet cs193pError where cs193pError isCS193pError{
structEmojiArtApp: App { var body: someScene { DocumentGroup(newDocument: { EmojiArtDocument()}) { config in EmojiArtDocumentView(document: config.document) } } }
your ViewModel must conform to ReferenceFileDocument
must implement Undo in your application
FileDocument
This protocol gets/puts the contents of a document from/to a file
1 2 3 4 5 6 7
init(configuration: ReadConfiguration) throws { iflet data = configuration.file.regularFileContents { // initialize yourself from the Data in that file } else { throwCocoaError(.fileReadCorruptFile) // should never happen } }
Writiing your document out to a file
1 2 3
funcfileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { FileWrapper(regularFileWithContents: /* myself as a Data*/) }
fileWrapper是因为iOS和Mac OS中的一些文件历来被存储为一个目录,其中包含一堆文件
ReferenceFileDocument
1 2 3
funcsnapshot(contentType: UTType) throws -> Snapshot { return/* my Model converted(possibly) to some other type, like a Data probably */ }
Snapshot type is a “don’t care”, but usually it’s a Data UTType is a Uniform Type Identifier
writting your document out to a file
1 2 3 4 5 6
funcfileWrapper( snapshot: Snapshot, configuration: WriteConfiguration ) throws -> FileWrapper { FileWrapper(regurationFileWithContents: /* snapshot converd to a Data*/) }
funcundoablyPerform(withundoManager: UndoManager?,doit: ()->Void) { let oldModel = model // save the model so we can undo back to it doit() undoManager?.registerUndo(withTarget: self){ myself in myself.model = oldModel } undoManager?.setActionName(operation) }
var observer: NSObjectProtocol? //a cookie to later "stop listening" with observer =NotificationCenter.default.addObserver( forName: Notification.Name object: nil, queue: .main ) { (notification: Notification) -> Voidin let info: Any?= notification.userInfo // info is usually a dictionary of notification-specific information }
NotificationCenter.default.removeObserver(observer) // to stop listening