How to Have a Swift Script Use Multiple Files

Is there a way to have a Swift script use multiple files

There's a better way!

#!/usr/bin/swift -frontend -interpret -enable-source-import -I.

import other_file // this imports other_file.swift in the same folder

funcFromOtherFile()

if you want to import files from ExampleFolder it would be like:

#!/usr/bin/swift -frontend -interpret -enable-source-import -I./ExampleFolder

import other_file // this imports ./ExampleFolder/other_file.swift

funcFromOtherFile()

How do I import other Swift files into a Swift script?

There's currently no way to import other swift files in a interpreted swift script. But you can concatenate all source files before executing them:

cat one.swift two.swift three.swift | swift -

If you're using the swift compiler, just add the files you want to compile together before the -o argument:

swiftc one.swift two.swift three.swift -o combined

No need to import them, they are already in the same module.

Get the Contents of multiple files in directory

First of all don't use outdated and objective-c-ish NSSearchPathForDirectoriesInDomains in Swift. Use the modernFileManager API.

Second of all don't use objective-c-ish NSDictionary(contentsOf to read property list data. Use PropertyListSerialization.

The function throws that means it hands over all possible errors to the caller. It filters the URLs in the directory by the plist extension and uses the map function to get the dictionary for each URL.

func getFiles() throws {
let documentDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let subFolderURL = documentDirectory.appendingPathComponent("MainFolder")
let allFiles = try FileManager.default.contentsOfDirectory(at: subFolderURL, includingPropertiesForKeys: nil)
let properListFiles = allFiles.filter{$0.pathExtension == "plist"}
tableViewData = try properListFiles.compactMap { url -> [String:String]? in
let data = try Data(contentsOf: url)
return try PropertyListSerialization.propertyList(from: data, format: nil) as? [String:String]
}
print(tableViewData)
}

Be aware that in sandboxed apps the Documents folder is located in the application container.

How to use classes defined in other files in a Swift script

This post asked a similar question, the solution there was to concatenate the files with a shell script:

TMPFILE=`mktemp /tmp/Project.swift.XXXXXX` || exit 1
trap "rm -f $TMPFILE" EXIT
cat *.swift > $TMPFILE
swift $TMPFILE

I haven't tested it though, so no idea if it works.



Related Topics



Leave a reply



Submit