SwiftPrettyPrint 提供比 Swift 标准库中的 print()
、debugPrint()
和 dump()
更易于人类阅读的输出。
@AppStorage
@Binding
@Environment
@EnvironmentObject
@FetchRequest
(仅属性包装器名称)@FocusedBinding
@FocusedState
(仅属性包装器名称)@FocusedValue
@GestureState
@Namespace
@ObservedObject
@Published
@ScaledMetric
@SceneStorage
(仅支持 URL
、Int
、Double
、String
和 Bool
类型)@State
@StateObject
@UIApplicationDelegateAdaptor
(仅属性包装器名称)@NSApplicationDelegateAdaptor
(仅属性包装器名称)print()
、debugPrint()
和 dump()
在 Swift 标准库中实现。但这些函数的输出有时难以阅读。
例如,有以下类型和值
enum Enum {
case foo(Int)
}
struct ID {
let id: Int
}
struct Struct {
var array: [Int?]
var dictionary: [String: Int]
var tuple: (Int, string: String)
var `enum`: Enum
var id: ID
}
let value = Struct(array: [1, 2, nil],
dictionary: ["one": 1, "two": 2],
tuple: (1, string: "string"),
enum: .foo(42),
id: ID(id: 7))
当您使用标准库时,您会得到以下结果。
print(value)
// Struct(array: [Optional(1), Optional(2), nil], dictionary: ["one": 1, "two": 2], tuple: (1, string: "string"), enum: SwiftPrettyPrintExample.Enum.foo(42), id: SwiftPrettyPrintExample.ID(id: 7))
debugPrint(value)
// SwiftPrettyPrintExample.Struct(array: [Optional(1), Optional(2), nil], dictionary: ["one": 1, "two": 2], tuple: (1, string: "string"), enum: SwiftPrettyPrintExample.Enum.foo(42), id: SwiftPrettyPrintExample.ID(id: 7))
dump(value)
// ▿ SwiftPrettyPrintExample.Struct
// ▿ array: 3 elements
// ▿ Optional(1)
// - some: 1
// ▿ Optional(2)
// - some: 2
// - nil
// ▿ dictionary: 2 key/value pairs
// ▿ (2 elements)
// - key: "one"
// - value: 1
// ▿ (2 elements)
// - key: "two"
// - value: 2
// ▿ tuple: (2 elements)
// - .0: 1
// - string: "string"
// ▿ enum: SwiftPrettyPrintExample.Enum.foo
// - foo: 42
// ▿ id: SwiftPrettyPrintExample.ID
// - id: 7
这些输出对于调试来说已经足够的信息,但不是易于人类阅读的输出。
使用 SwiftPrittyPrint,它看起来像这样
Pretty.print(value)
// Struct(array: [1, 2, nil], dictionary: ["one": 1, "two": 2], tuple: (1, string: "string"), enum: .foo(42), id: 7)
Pretty.prettyPrint(value)
// Struct(
// array: [
// 1,
// 2,
// nil
// ],
// dictionary: [
// "one": 1,
// "two": 2
// ],
// tuple: (
// 1,
// string: "string"
// ),
// enum: .foo(42),
// id: 7
// )
当然,我们也可以将 SwiftPrettyPrint 与 LLDB 一起使用。(通过使用 LLDB 集成,您可以使用更短的关键字,例如 _p
和 _pp
)
(lldb) e Pretty.prettyPrint(value)
Struct(
array: [
1,
2,
nil
],
dictionary: [
"one": 1,
"two": 2
],
tuple: (
1,
string: "string"
),
enum: .foo(42),
id: 7
)
SwiftPrettyPrint 具有以下四个基本功能
print(label: String?, _ targets: Any..., separator: String, option: Pretty.Option)
prettyPrint(label: String?, _ targets: Any..., separator: String, option: Pretty.Option)
printDebug(label: String?, _ targets: Any..., separator: String, option: Pretty.Option)
prettyPrintDebug(label: String?, _ targets: Any..., separator: String, option: Pretty.Option)
唯一必需的参数是 targets
,它通常可以描述如下。
let array: [URL?] = [
URL(string: "https://github.com/YusukeHosonuma/SwiftPrettyPrint"),
nil
]
Pretty.print(array)
// => [https://github.com/YusukeHosonuma/SwiftPrettyPrint, nil]
Pretty.prettyPrint(array)
// =>
// [
// https://github.com/YusukeHosonuma/SwiftPrettyPrint,
// nil
// ]
Pretty.printDebug(array)
// => [Optional(URL("https://github.com/YusukeHosonuma/SwiftPrettyPrint")), nil]
Pretty.prettyPrintDebug(array)
// =>
// [
// Optional(URL("https://github.com/YusukeHosonuma/SwiftPrettyPrint")),
// nil
// ]
您可以使用类似于 Ruby 的基于操作符的别名 API。
不需要用括号括起来,这对于长表达式很方便。
p >>> 42
// => 42
p >>> 42 + 2 * 4 // It can also be applied to expression
// => 50
p >>> String(string.reversed()).hasSuffix("eH")
// => true
pp >>> ["Hello", "World"]
// =>
// [
// "Hello",
// "World"
// ]
操作符语法 | 等价于 |
---|---|
p >>> 42 |
Pretty.print(42) |
pp >>> 42 |
Pretty.prettyPrint(42) |
pd >>> 42 |
Pretty.printDebug(42) |
ppd >>> 42 |
Pretty.prettyPrintDebug(42) |
您可以配置格式选项,共享或通过参数传递。
您可以在 pretty-print 中指定缩进大小,如下所示
// Global option
Pretty.sharedOption = Pretty.Option(indentSize: 4)
let value = (bool: true, array: ["Hello", "World"])
// Use `sharedOption`
Pretty.prettyPrint(value)
// =>
// (
// bool: true,
// array: [
// "Hello",
// "World"
// ]
// )
// Use option that is passed by argument
Pretty.prettyPrint(value, option: Pretty.Option(prefix: nil, indentSize: 2))
// =>
// (
// bool: true,
// array: [
// "Hello",
// "World"
// ]
// )
输出字符串可以是 ANSI 彩色的。
着色选项指定如下
Pretty.sharedOption = Pretty.Option(colored: true)
在此配置下,可以在 AppCode 中实现以下输出
它仅适用于支持 ANSI 颜色的控制台(例如 AppCode、Terminal.app)。这**不**包括 Xcode 调试控制台。
另请参阅 终端 部分。
您可以指定全局前缀和标签(例如,变量名),如下所示
Pretty.sharedOption = Pretty.Option(prefix: "[DEBUG]")
let array = ["Hello", "World"]
Pretty.print(label: "array", array)
// => [DEBUG] array: ["Hello", "World"]
Pretty.p("array") >>> array
// => [DEBUG] array: ["Hello", "World"]
将 .osLog
应用于 Option.outputStrategy
使输出显示在 Console.app
中
xcode-debug-console 中的输出将如下所示。
Debug.sharedOption = Debug.Option(outputStrategy: .osLog)
let dog = Dog(id: DogId(rawValue: "pochi"), price: Price(rawValue: 10.0), name: "ポチ")
Debug.print(dog)
// => 2020-04-02 11:51:10.766231+0900 SwiftPrettyPrintExample[41397:2843004] Dog(id: "pochi", price: 10.0, name: "ポチ")
请复制以下内容并添加到您的 ~/.lldbinit
(如果该文件不存在,请创建该文件)
command regex _p 's/(.+)/e -l swift -o -- var option = Pretty.sharedOption; option.prefix = nil; Pretty.print(%1, option: option)/'
command regex _pp 's/(.+)/e -l swift -o -- var option = Pretty.sharedOption; option.prefix = nil; Pretty.prettyPrint(%1, option: option)/'
或通过 lowmad 安装
$ lowmad install https://github.com/YusukeHosonuma/SwiftPrettyPrint.git
注意: 如果您已经通过 lowmad 安装了 1.1.0 或更早版本的 SwiftPrettyPrint,请在更新之前手动删除脚本。(例如,rm /usr/local/lib/lowmad/commands/YusukeHosonuma-SwiftPrettyPrint/swift_pretty_print.py
)
这使您可以在调试控制台中使用 lldb 命令,如下所示
(lldb) e -l swift -- import SwiftPrettyPrint # If needed
(lldb) _p dog
Dog(id: "pochi", price: 10.0, name: "ポチ")
(lldb) _pp dog
Dog(
id: "pochi",
price: 10.0,
name: "ポチ"
)
当运行 iOS 模拟器 或 macOS 时,SwiftPrettyPrint 会自动将日志文件输出到以下文件:
因此,您可以从其他工具(例如 tail
或 grep
等)读取它们。
$ tail -F /tmp/SwiftPrettyPrint/output-colored.log
output-colored.log
是 ANSI 着色的,因此在终端上看起来很漂亮。
您可以通过 Debug.Option.theme
属性自定义终端 ANSI 颜色,如下所示。
let theme = ColorTheme(
type: { $0.green().bold() },
nil: { $0.yellow() },
bool: { $0.yellow() },
string: { $0.blue() },
number: { $0.cyan() },
url: { $0.underline() }
)
Debug.sharedOption = Debug.Option(theme: theme)
可以使用 ColorizeSwift 轻松指定 ANSI 颜色。
请将新主题添加到 ColorTheme.swift 并创建 PR。
public struct ColorTheme {
...
+ public static let themeName = ColorTheme(
+ type: { ... },
+ nil: { ... },
+ bool: { ... },
+ string: { ... },
+ number: { ... },
+ url: { ... }
+ )
public var type: (String) -> String
public var `nil`: (String) -> String
...
谢谢!
您可以在任何 View
上使用 prettyPrint()
和 prettyPrintDebug()
。
// Standard API.
Text("Swift")
.prettyPrint()
.prettyPrintDebug()
// You can specify label if needed.
Text("Swift")
.prettyPrint(label: "🍎")
.prettyPrintDebug(label: "🍊")
此扩展对于检查内部结构很有用。
您可以在 Combine 框架中使用 prettyPrint()
操作符。
[[1, 2], [3, 4]]
.publisher
.prettyPrint("🍌")
.sink { _ in }
.store(in: &cancellables)
// =>
// 🍌: receive subscription: [[1, 2], [3, 4]]
// 🍌: request unlimited
// 🍌: receive value:
// [
// 1,
// 2
// ]
// 🍌: receive value:
// [
// 3,
// 4
// ]
// 🍌: receive finished
您可以指定 when:
和 format:
。
[[1, 2], [3, 4]]
.publisher
.prettyPrint("🍌", when: [.output, .completion], format: .singleline)
.sink { _ in }
.store(in: &cancellables)
// =>
// 🍌: receive value: [1, 2]
// 🍌: receive value: [3, 4]
// 🍌: receive finished
您也可以使用别名 API p()
和 pp()
。
[[1, 2], [3, 4]]
.publisher
.p("🍎") // Output as single-line
.pp("🍊") // Output as multiline
.sink { _ in }
.store(in: &cancellables)
pod "SwiftPrettyPrint", "~> 1.2.0", :configuration => "Debug" # enabled on `Debug` build only
示例应用程序 在这里。
github "YusukeHosonuma/SwiftPrettyPrint"
将以下行添加到您的 Package.swift
文件中的依赖项
.package(url: "https://github.com/YusukeHosonuma/SwiftPrettyPrint.git", .upToNextMajor(from: "1.2.0"))
最后,将“SwiftPrettyPrint”作为您的任何目标的依赖项包含
let package = Package(
// name, platforms, products, etc.
dependencies: [
.package(url: "https://github.com/YusukeHosonuma/SwiftPrettyPrint.git", .upToNextMajor(from: "1.2.0")),
// other dependencies
],
targets: [
.target(name: "<your-target-name>", dependencies: ["SwiftPrettyPrint"]),
// other targets
]
)
或者,使用 Xcode 集成。此功能自 Xcode 10 起可用。
如果您不想在调试时编写 import
语句。
我们建议创建 Debug.swift
并将任何类型声明为 typealias
,如下所示
// Debug.swift
#if canImport(SwiftPrettyPrint)
import SwiftPrettyPrint
typealias Debug = SwiftPrettyPrint.Pretty // You can use short alias such as `D` too.
#endif
您不再需要在每个源文件中编写 import
语句。
// AnySource.swift
Debug.print(42)
Debug.prettyPrint(label: "array", array)
注意:这不能用于基于操作符的 API,例如 p >>>
。(这是 Swift 语言的限制)
要求
make test
或最新版本的 Xcode 来运行单元测试。执行 make setup
以将开发工具安装到系统(不包括 Xcode 11.3)。
$ make help
setup Install requirement development tools to system and setup (not include Xcode 11.3)
build swift - build
test swift - test
xcode swift - generate xcode project
format format sources by SwiftFormat
lint cocoapods - lint podspec
release cocoapods - release
info cocoapods - show trunk information
由 Penginmura 开发。