一个用于使用 GraphViz 的 Swift 包。
import GraphViz
var graph = Graph(directed: true)
let a = Node("a"), b = Node("b"), c = Node("c")
graph.append(Edge(from: a, to: b))
graph.append(Edge(from: a, to: c))
var b_c = Edge(from: b, to: c)
b_c.constraint = false
graph.append(b_c)
// Render image to SVG using dot layout algorithm
graph.render(using: .dot, to: .svg) { result in
guard .success(let data) = result,
let svg = String(data: data, encoding: .utf8)
else { return }
print(svg)
}
digraph {
a -> b
a -> c
b -> c [constraint=false]
}
注意:
render(using:to:)
及相关方法需要在你的系统上安装 GraphViz。
import GraphViz
let graph = Graph(directed: true) {
"a" --> "b"
"a" --> "c"
("b" --> "c").constraint(false)
}
注意:Swift 5.1 可能需要显式的类型转换表达式,以协调自定义边运算符(如
-->
)的使用。(error: ambiguous reference to member '--->'
)
您可以通过运行以下命令在您的系统上安装 GraphViz
# macOS
$ brew install graphviz
# Linux (Ubuntu)
$ sudo apt-get install graphviz
重要提示:如果您将 GraphViz 添加到您的 macOS 应用程序并使用 Homebrew 安装了系统依赖项,Xcode 可能会发出类似以下内容的错误消息
Warning: Could not load "/usr/lib/graphviz/libgvplugin_gdk.so.6" It was found, so perhaps one of its dependents was not. Try ldd.
一种解决方案是运行以下命令来签署依赖项(将
MyName (MyTeam)
替换为您的开发者帐户名和团队名)$ codesign -f -s "Apple Development: MyName (MyTeam)" /usr/local/opt/*/lib/*.dylib $ codesign -f -s "Apple Development: MyName (MyTeam)" /usr/local/Cellar/*/*/lib/*.dylib
将 GraphViz 包添加到 Package.swift
中的目标依赖项
import PackageDescription
let package = Package(
name: "YourProject",
dependencies: [
.package(
url: "https://github.com/SwiftDocOrg/GraphViz",
from: "0.4.1"
),
]
)
将 GraphViz
添加为您的目标依赖项
targets: [
.target(
name: "YourTarget",
dependencies: ["GraphViz"]),
MIT
Mattt (@mattt)