为什么我不能在字符串上使用 write(toFile:) 属性?

Why can't I use write(toFile: ) property on a string?

我正在学习用 Swift 的某个早期版本编写的教程,该教程教我如何 read/write 在 Swift3 中创建 .txt 文件。到目前为止,Xcode 在让我知道我在使用旧语法并为我将其更改为最新语法方面做得很好。但是,我遇到了一些在 Swift 的旧版本中有效但在当前版本中无效的方法。

class ViewController: UIViewController {

    // MARK: Properties

    @IBOutlet weak var monthToEditTextField: UITextField!
    @IBOutlet weak var bedTimeTextField: UITextField!
    @IBOutlet weak var wakeTimeTextField: UITextField!
    @IBOutlet weak var theLabel: UILabel!

    @IBAction func saveButton(_ sender: UIButton)
    {
        var theMonth = monthToEditTextField.text
        var bedTime = bedTimeTextField.text
        var wakeTime = wakeTimeTextField.text

        var stringForTXTFile = "The user's info is: \(theMonth), \(bedTime), \(wakeTime)"

        let fileManager = FileManager.default

        if (!fileManager.fileExists(atPath: filePath))
        {
            var writeError: NSError?
            let fileToBeWritten = stringForTXTFile.write(toFile: // This is where the problem is
        }   
    }

当我输入

stringForTXTFile.write

我收到这个错误框

我需要做什么才能使用 "write" 属性?

写入文件在 Swift3 中不再 return Bool。它抛出,所以只需删除 let fileToBeWritten = 并使用 do try catch error 处理。如果操作成功,任何需要 运行 的代码都需要放在 do try 大括号内的代码下方。您还可以使用 guard 来解包您的文本字段可选字符串。像这样尝试:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var monthToEditTextField: UITextField!
    @IBOutlet weak var bedTimeTextField: UITextField!
    @IBOutlet weak var wakeTimeTextField: UITextField!
    @IBOutlet weak var theLabel: UILabel!
    let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("textFile.txt")
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBAction func save(_ sender: UIButton) {
        guard
            let theMonth = monthToEditTextField.text,
            let bedTime = bedTimeTextField.text,
            let wakeTime = wakeTimeTextField.text
            else { return }

        let stringForTXTFile = "The user's info is: \(theMonth), \(bedTime), \(wakeTime)"
            do {
                try stringForTXTFile.write(toFile: fileURL.path, atomically: true, encoding: .utf8)
                // place code to be executed here if write was successful
            } catch {
                print(error.localizedDescription)
            }
    }

    @IBAction func load(_ sender: UIButton) {
        do {
            theLabel.text = try String(contentsOf: fileURL)
        } catch {
            print(error.localizedDescription)
        }
    }
}