First things first. When posting code to these forums, place three backticks ```
on a line by themselves and then three more backticks ```
on a line by themselves and paste your code in between those two lines so that it will be formatted properly.
This makes it far easier to read and also makes it easier for other posters to copy/paste the code in order to test solutions and such.
Now, on to the code…
@State var lines = [""]
You don’t need this, as the only place you are using lines
is as a temporary variable in the action handler of a Button
.
@State var notes = [""]
If notes
is empty to start with, use either of these forms instead:
@State var notes: [String] = []
//or
@State var notes = [String]()
Now, to the meat of your "Read File"
button.
let url = Bundle.main.url(forResource: "TextFile", withExtension: "txt")!
let text = try! String(contentsOf: url)
@State var lines = text.split(separator: "\n")
for number in lines {
notes[number].description = lines[number].description
}
notes
is an array of String
s (i.e., you previously defined it as @State var notes = [""]
). String
has no settable description
property, so I’m not sure what you are trying to achieve here.
When you do a for X in Y
loop as you have here, the part designated as X
is one example of the collection of things called Y
, so number
is one line in the lines
array. As such, you wouldn’t use number
as an index into your lines
array.
But, those two things aside, the loop is entirely unnecessary here anyway. All you are doing is assigning each line in lines
to the notes
array. Instead, just assign the lines directly to notes
:
let url = Bundle.main.url(forResource: "TextFile", withExtension: "txt")!
let text = try! String(contentsOf: url)
notes = text.split(separator: "\n")
Finally, I’m not sure what this function is for:
func getStr(str: String) → String{
return str
}
It does absolutely nothing. You take a String
and return the exact same String
. It’s pointless.
Make those changes, see what happens. You’ll probably (definitely) still have errors but they’ll be different ones.
And provide the sample data that Chris requested.
Then let us know how it goes.