swift - 使用 Cocoapods 依赖运行 Swift 脚本

标签 swift cocoa scripting dependencies cocoapods

我有一个使用 Cocoapods 的 iOS 项目。我使用的其中一个 pod 是 https://github.com/mattrubin/OneTimePassword .我写了一个小包装器来包装这个 pod 的功能——在我的例子中,它是在当前时间打印出密码。这一切都很好。

我想用 Swift 编写一个基本上从命令行进行打印的脚本。我按照这里的教程 https://krakendev.io/blog/scripting-in-swift但是当我尝试编译我的脚本时,编译器认为我的框架不可用..

这是我的脚本:

#!/usr/bin/swift

// import OneTimePassword // This is the Pod I'm trying to use. I get the error: error: no such module 'OneTimePassword'

print(MyWrapperClass.shared.printPwd()) // error: use of unresolved identifier 'MyWrapperClass'

我正在使用命令 swiftc main.swift -o main

进行编译

最佳答案

我正在尝试做同样的事情。此页面是搜索“swift scripting cocoapods”的最佳结果,但仍未得到答复让我认为还没有太多人尝试使用 swift 编写脚本。

First of all, if you're compiling your code then it's not really a script, just a tiny program. The point of the "#!" line in a script is so you can mark it as executable (yes the source file, with chmod a+x blah.swift), put it in a executable path like /usr/local/bin, type blah.swift in your shell. The swift compiler knows to build then run it for you (yes, rebuilds it every time because swift is not an interpreter, but its not unreasonable to do this for tiny code). It's ok to omit the file extension from your swift file if you want the command you type to be just "blah".

遗憾的是,似乎没有什么能像 perl 的 CPAN 一样可以将 swift 包添加到您的系统并允许它在简单的可执行 swift 脚本中使用。 Swift Package Manager 和 cocoapods-rome 都假设您的脚本有一个项目源目录,有点假设要构建它然后安装二进制文件(尽管这似乎有点像您期望的那样)。 编辑:我错了,下面段落中提到的东西毕竟会这样做。

我发现非常接近的是“马拉松”https://github.com/johnsundell/marathon ,这使得创建、运行、调试具有依赖关系的脚本变得容易,而无需暴露其源目录和废话。不幸的是,您失去了脚本作为标记为可执行文件并按名称运行的文件的简单性,您的脚本文件隐藏在某个托管位置并通过marathon run blah执行。命令。然而,shell 别名/函数可以为您隐藏那些困惑的业务,这就是我打算做的。

marathon 的作者还有一组指向用于 swift 脚本编写的工具和包的链接:https://github.com/JohnSundell/SwiftScripting

编辑: 它看起来像特殊的 shebang 行 #!/usr/bin/env marathon run毕竟会让一个人使用带有马拉松式安装的 pod/包的裸脚本。如果你想利用这个,7ball,那么这样做:

  • 安装 marathon(嗯,自制版本已经过时,请按照 Swift 包管理器的说明进行操作)
  • 将脚本中的 shebang 行从 #!/usr/bin/swift 更改为以上
  • 取消注释您的“导入”行并在其后添加特殊的马拉松注释,如下所示:import OneTimePassword // marathon:https://github.com/mattrubin/OneTimePassword.git
  • (或者使用 marathon add https://github.com/mattrubin/OneTimePassword.git 提前将它安装到 marathon 中,并且不要在“导入”行上添加那个有趣的注释)
  • 运行“./main.swift”

关于swift - 使用 Cocoapods 依赖运行 Swift 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45744537/

相关文章:

linux - 如何从文本文件中删除换行符?

ios - 分配 NSTimer 时不调用 Deinit

swift - 将反射对象的属性转换回其原始类型

swift - 如何滚动到 UICollectionView 的底部?

objective-c - NSTableView 中每个图像都有不同的工具提示

swift - 基于文档的 Swift 应用程序中看似黑暗的 Cocoa 绑定(bind)艺术

cocoa - 确定应用程序是否是从 AppleScript 启动的

ide - 哪种 TextEditor 最容易为新的脚本语言定制?

node.js - 安排 Heroku 每 10 分钟左右重新启动 dynos

ios - 当应用程序失去焦点时,基于 BLE 值的 Swift 通知