Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

swift - How can I enumerate through a hard coded directory?

I cannot work out why hard coding a directory doesn’t work when trying to enumerate through a directory.

I have written a simple function to open a dialog and return a selected folder. The function includes a starting directory (directoryURL below):

func selectFolder(title: String, directoryURL: String = ".") -> String? {
    let openPanel=NSOpenPanel();
    openPanel.title = title
    openPanel.allowsMultipleSelection = false
    openPanel.canChooseDirectories = true
    openPanel.canChooseFiles = false
    openPanel.canCreateDirectories = true
    openPanel.directoryURL = URL(fileURLWithPath: directoryURL)
    if(openPanel.runModal() == NSApplication.ModalResponse.OK) {
        return directoryURL;        //  This won’t work
        return openPanel.url!.path  //  This is OK
    }
    else {
        return nil
    }
}

In the above function I have prematurely returned with the original directory which is a string, so the whole process is ignored. If I comment out the first return statement, then it will return the selected directory, which is also a string.

Here is a SwiftUI button to test the function:

Button(action: {
    let fileManager = FileManager.default
    let sourceFolder = selectFolder(title: "test", directoryURL: "/path/to/folder")
    if let enumerator = fileManager.enumerator(
        at: URL(fileURLWithPath: sourceFolder!),
        includingPropertiesForKeys: [.isRegularFileKey],
        options: [.skipsHiddenFiles,.skipsPackageDescendants]
    ) {
        for case let fileURL as URL in enumerator {
            print("fileURL: (fileURL)")
        }
    }
}) {
    Text("Test")
}

The purpose is to iterate through the contents of the directory, including subdirectories.

If I return the hard coded string from the function, the for case let fileURL as URL in enumerator statement has nothing, and there are no results. There are no errors either.

If I return the openPanel.url!.path, the for case … statement prints the directory contents as expected.

I can’t see what the function returns which is different from the original string.

What can I do to get a hard coded string to work?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...