I 'm. struggling with the following code "import SwiftUI
struct ContentView: View {
var pictures = [String]()
var body: some View {
let fm = FileManager.default
let path = Bundle.main.resourcePath!
let items = try! fm.contentsOfDirectory(atPath: path)
for item in items {
if let item = item.hasPrefix("nssl") {
pictures.append(item)
}
}
print(pictures)
}
}
while before it was :
class ViewController: UIViewController { var pictures = [String] "()
override func viewDidLoad() {
super.viewDidLoad()
let fm = FileManager.default let path = Bundle.main.resourcePath! let items = try! fm.contentsOfDirectory(atPath: path)
and it was working
Much clearer.
You should do the assignment in init or in onAppear, like this:
struct ContentView: View {
@State var pictures = [String]() // need @State
var body: some View {
let fm = FileManager.default
let path = Bundle.main.resourcePath!
let items = try! fm.contentsOfDirectory(atPath: path)
Text("Hello")
.onAppear() {
for item in items {
if item.hasPrefix("nssl") {
pictures.append(item)
}
}
print(pictures)
}
}
}