Commit 896d36505a
Verified · cmc
Layout: unified · split
LibreEdit/ContentView.swift +4 −6
| @@ -9,18 +9,15 @@ import SwiftUI | |||
| 9 | import UniformTypeIdentifiers | 9 | import UniformTypeIdentifiers |
| 10 | 10 | ||
| 11 | struct TextFile: FileDocument { | 11 | struct TextFile: FileDocument { |
| 12 | // tell the system we support only plain text | ||
| 13 | static var readableContentTypes = [UTType.plainText] | 12 | static var readableContentTypes = [UTType.plainText] |
| 14 | |||
| 15 | // by default our document is empty | ||
| 16 | var text = "" | 13 | var text = "" |
| 17 | 14 | ||
| 18 | // a simple initializer that creates new, empty documents | 15 | // Initialize a new document |
| 19 | init(initialText: String = "") { | 16 | init(initialText: String = "") { |
| 20 | text = initialText | 17 | text = initialText |
| 21 | } | 18 | } |
| 22 | 19 | ||
| 23 | // this initializer loads data that has been saved previously | 20 | // Load an existing document |
| 24 | init(configuration: ReadConfiguration) throws { | 21 | init(configuration: ReadConfiguration) throws { |
| 25 | if let data = configuration.file.regularFileContents { | 22 | if let data = configuration.file.regularFileContents { |
| 26 | text = String(decoding: data, as: UTF8.self) | 23 | text = String(decoding: data, as: UTF8.self) |
| @@ -29,13 +26,14 @@ struct TextFile: FileDocument { | |||
| 29 | } | 26 | } |
| 30 | } | 27 | } |
| 31 | 28 | ||
| 32 | // this will be called when the system wants to write our data to disk | 29 | // Save document data to file |
| 33 | func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { | 30 | func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { |
| 34 | let data = Data(text.utf8) | 31 | let data = Data(text.utf8) |
| 35 | return FileWrapper(regularFileWithContents: data) | 32 | return FileWrapper(regularFileWithContents: data) |
| 36 | } | 33 | } |
| 37 | } | 34 | } |
| 38 | 35 | ||
| 36 | // Counts all words in the opened file | ||
| 39 | func countWords(text: String) -> Int { | 37 | func countWords(text: String) -> Int { |
| 40 | let words = text.split { $0 == " " || $0.isNewline } | 38 | let words = text.split { $0 == " " || $0.isNewline } |
| 41 | return words.count | 39 | return words.count |