首页 > swift 包管理怎么用

swift 包管理怎么用

请教一下,swift包管理怎么用?我创建了一个swift项目,然后在根目录创建了一个Package.swift文件,
代码如下:

import PackageDescription

let package = Package(
    name: "Format",
    dependencies: [
        .Package(url: "https://github.com/marmelroy/Format.git", majorVersion: 1),
    ]
)

但是这里“ PackageDescription”报错,系统提示没有这个库,使用swift build也无效。

这个是什么问题,请大神解答一下。


首先我的理解是 SwiftPM (Swift Package Manager) 不是在 Xcode 里面这样使用的。而是直接在命令行里进行的。

官方简介:

The Swift Package Manager is a tool for managing the distribution of Swift code. It’s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies.

大概意思是, 你可以直接使用 SwiftPM 来进行 下载、编译、链接 你的 Swift 代码和依赖

而在 OS X 上面安装的 Xcode 里面目前(Xcode 7.3)是没有带上 SwiftPM 这个工具的,所以当你执行 swift build 时会报错,如下:

$ swift build
error: unable to invoke subcommand: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-build (No such file or directory)

所以,你需要去下载开发版本的 swift。以下为解决方案:

安装

  1. 去官方下载 Swift Trunk Development (master) 版本(即 dev 版本, 与 Xcode 使用版本不冲突)。传送门

    • 下载下来应该是 swift-DEVELOPMENT-SNAPSHOT-2016-03-24-a-osx.pkg 这样一个文件 大约 200MB

  2. 将最新的 Swift 版本配置到环境变量里。打开命令行执行

$ export PATH=/Library/Developer/Toolchains/swift-latest.xctoolchain/usr/bin:"${PATH}"

然后检查是否安装成功

$ swift build --version
Apple Swift Package Manager 0.1

使用

首先,创建一个空目录

$ cd ~/Desktop
$ mkdir helloSwiftPM 
$ cd helloSwiftPM

然后,初始化这个目录。

$ swift build --init

编译

$ swift build

运行

$ .build/debug/helloSwiftPM
Hello, world!

到此就 OK 了 ?

参考:
官网 Getting Started
官网 Swift Package Manager
Swift.gg 使用 SwiftPM 创建新的包

【热门文章】
【热门文章】