我在单个行上有一个大约30个字的文本文件,名为GoodWords.txt,我想使用该文件作为数组的源。
一旦SwiftUI问世,我就开始学习Swift,所以我真的开始学习没有Swift背景的SwiftUI。
一些伟大的和长期的解决方案是在不同的网站,包括这个,但他们都在Swift而不是Swift me所以输出的打印是没有帮助的。
以下是最有用的资源:快速的文本文件到字符串数组
最后,我尝试将版本5 1复制并粘贴到一个SwiftUI文件中,但是我不知道函数应该去哪里,或者在哪里调用它。
我在我的项目中包含了文本文件"GoodWords.txt“。下面是我的代码(我将省去其他版本无法工作的时间):
//
// ImportTxtToArray.swift
// GoodWord
//
// Created by Gabe Mott on 11/16/22.
//
import SwiftUI
struct ImportTxtToArray: View {
func printLine() -> String {
let filename = "GoodWords"
var text: String
var myCounter: Int
guard let file = Bundle.main.url(forResource: "GoodWords", withExtension: "txt")
else {
fatalError("Couldn't find \(filename) in bundle.")
}
do {
let contents = try String(contentsOf: file, encoding: String.Encoding.utf8 )
let lines = contents.split(separator:"\n")
print(contents)
print(lines)
myCounter = lines.count
print(myCounter)
text = String(myCounter)
} catch {
return (error.localizedDescription)
}
return text
}
var body: some View {
printLine()
Text("\(text)")
}
}
struct ImportTxtToArray_Previews: PreviewProvider {
static var previews: some View {
ImportTxtToArray()
}
}我得到的错误是“找不到范围内的文本”。
我很想知道如何做到这一点,但也有一些解释可以帮助我理解如何阅读一个Swift的答案,并将其输入SwiftUI。
这是我目前的主要问题:如何将文本文件作为数组访问到我的SwiftUI文件中。
这张图片/截图只是给出了我为什么要学这个的背景。这是代码和我正在制作的代码的一个非常粗糙的例子(BTW在我的下一个问题中,我依靠颜色变量来使计数器工作,我试图删除颜色变量,所有的东西都中断了,但我离题了。)
我尝试了很多古老的答案(斯威夫特3),试过:守卫,做,抓住……我所得到的只是错误。大多数解决方案适用于更详细的高级情况。我正在寻找最快,最有效的方式,使我的文本文件为我的数组中的单个单词的来源。终极目标是动画,就像在文字中循环一样。
发布于 2022-11-17 01:39:55
感谢伊莱的回答/工作代码!这是笨重的,不是最终的,但解决了核心问题。
// ImportTxtToArray.swift
// GoodWord
//
// Created by Gabe Mott on 11/16/22.
//
import SwiftUI
struct ImportTxtToArray: View {
//eli helped with this, pass func but why do so many variables go here and eli put all at bottom
@State var counter = 0
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
HStack {
Text ("Good")
Text("\(printLine())")
// done for day , thought i could nail this:
// Text("\(printLine[counter])")
// .onReceive(timer) { tm in
// guard counter + 1 < Self.colors.count else {
// timer.upstream.connect().cancel()
// return
// }
//
// counter += 1
// color = Self.colors[counter]
// }
}
}
func printLine() -> String {
let filename = "GoodWords"
var text: String
var myCounter: Int
guard let file = Bundle.main.url(forResource: "GoodWords", withExtension: "txt")
else {
fatalError("Couldn't find \(filename) in bundle.")
}
do {
let contents = try String(contentsOf: file, encoding: String.Encoding.utf8 )
let lines = contents.split(separator:"\n")
myCounter = lines.count
print(myCounter)
text = String(contents)
// text = String(myCounter)
} catch {
return (error.localizedDescription)
}
return text
}
}
[1]: https://i.stack.imgur.com/PIWpC.jpghttps://stackoverflow.com/questions/74466843
复制相似问题