Read file in swift, iOS playground

后端 未结 2 853
一向
一向 2021-01-01 23:55

Having searched through the many (many!) swift playground questions to even craft this code, I\'m still struggling.

I\'ve placed a text file in the Re

2条回答
  •  感动是毒
    2021-01-02 00:41

    You can try creating a class for opening and saving your files:

    update: Xcode 10 • Swift 4.2

    class File {
        class func open(_ path: String, encoding: String.Encoding = .utf8) -> String? {
            if FileManager.default.fileExists(atPath: path) {
                do {
                    return try String(contentsOfFile: path, encoding: encoding)
                } catch {
                    print(error)
                    return nil
                }
            }
            return  nil
        }
    
        class func save(_ path: String, _ content: String, encoding: String.Encoding = .utf8) -> Bool {
            do {
                try content.write(toFile: path, atomically: true, encoding: encoding)
                return true
            } catch {
                print(error)
                return false
            }
        }
    }
    

    usage: File.save

    let stringToSave: String = "Your text"
    
    let didSave = File.save("\(NSHomeDirectory())/Desktop/file.txt", stringToSave) 
    
    if didSave { print("file saved") } else { print("error saving file") } 
    

    usage: File.open

    if let loadedData = File.open("\(NSHomeDirectory())/Desktop/file.txt") {
        print(loadedData)
    } else {
        println("error reading file")
     }  
    

    If you prefer working with URLs (as I do and recommended by Apple):
    Note that in Swift 4, the class URL already exists.

    class Url {
        class func open(url: URL) -> String? {
            do {
                return try String(contentsOf: url, encoding: String.Encoding.utf8)
            } catch {
                print(error)
                return nil
            }
        }
    
        class func save(url: URL, fileContent: String) -> Bool {
            do {
                try fileContent.write(to: url, atomically: true, encoding: .utf8)
                return true
            } catch {
                print(error)
                return false
            }
        }
    }
    

提交回复
热议问题