在Swift Playground中编写文件出错

时间:2018-02-15 00:10:41

标签: swift csv fwrite swift-playground

不知道为什么我在这里收到错误。我创建了文件夹' Shared Playground Data'按照指示在文件中。有没有人有任何见解?

import PlaygroundSupport
import Foundation

var fileName = "Csv.csv"
var csvText = "Date,Task,Time Started,Time Ended\n"
fileName.append(csvText)

let fileUrl = playgroundSharedDataDirectory.appendingPathComponent(fileName)
do {
try fileName.write(to: fileUrl, atomically: true, encoding: .utf8)
} catch {print("error")}

2 个答案:

答案 0 :(得分:2)

你的代码毫无意义。为什么要将列标题附加到文件名?为什么要将fileName的内容写入fileUrl

您可能需要以下内容:

let fileName = "Csv.csv"
let csvText = "Date,Task,Time Started,Time Ended\n"

let fileUrl = playgroundSharedDataDirectory.appendingPathComponent(fileName)
do {
    try csvText.write(to: fileUrl, atomically: true, encoding: .utf8)
} catch {
    print(error)
}

答案 1 :(得分:0)

我不知道是哪个 Xcode 引入了这个错误,但是在 Xcode 13 beta 2 上的 Playgrounds 找不到 playgroundSharedDataDirectory 目录,所以改为这样做:

Swift 5 版本

let docDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileName = "Csv.csv"
let outputFileUrl = docDirectory.appendingPathComponent(fileName)

let csvText = "Date,Task,Time Started,Time Ended\n"

do {
  try csvText.write(to: outputFileUrl, atomically: true, encoding: .utf8)
} catch {
  print (error)
}