首页 > 解决方案 > 将 JSON 文件添加到 Swift Playgrounds

问题描述

我在 swift 游乐场上创建了一本游乐场书,但我不知道如何将 JSON 文件添加到目录中。您可以将 JSON 文件添加到 swift playground (ipad) 吗?如果是这样,怎么做?

标签: jsonswiftipad-playgrounds

解决方案


单击 swift 右上角的“+”图标,Playgrounds然后通过单击Insert from...选项选择 json 文件。然后使用下面的代码从json文件中读取数据。

import Foundation

do {
    guard let fileUrl = Bundle.main.url(forResource: "filename", withExtension: "json") else { fatalError() }
    let text = try String(contentsOf: fileUrl, encoding: String.Encoding.utf8)
    print(text)
} catch {
    print(error)
}

推荐阅读