BSON 7.0.28

BSON 7.0.28

Joannis OrlandosRobbert Brandsma维护。



BSON 7.0.28

BSON

Swift 4.2 Swift 5.3 License Build Status

BSON 7是一个快速的BSON库。它符合整个BSON规范测试套件。库按需解析二进制数据,直到最后一刻才延迟复制。

BSON按照BSON规范1.1版本进行解析和生成。

请务必阅读我们的完整文档

安装

BSON使用Swift包管理器。在您的Package.swift文件中添加BSON为依赖项

.package(url: "https://github.com/OpenKitten/BSON.git", from: "7.0.0")

同时,别忘了将"BSON"作为依赖项添加到您的目标中。

基本用法

使用字典字面量创建文档

var userDocument: Document = [
	"username": "Joannis",
	"online": true,
	"age": 20,
	"pi_constant": 3.14,
	"profile": [
		"firstName": "Joannis",
		"lastName": "Orlandos"
	]
]

let favouriteNumbers: Document = [1, 3, 7, 14, 21, 24, 34]

userDocument["favouriteNumbers"] = favouriteNumbers

像在Swift数组中一样访问数组中的值,像在字典中一样访问对象中的值。

let favouriteNumber = favouriteNumbers[0]
let usernameValue = userDocument["username"]

以简洁的方式提取类型

let username = String(userDocument["username"]) // "Joannis"
let isOnline = Bool(userDocument["online"]) // true
let age = Int(userDocument["age"]) // 20
let pi = Double(userDocument["pi_constant"]) // 3.14

通过使用下面的JSON结构(假设这表示为BSON)来轻松链式使用下标,找到结果而无需麻烦(如下所示)

{
  "users": [
  	{
  		"username": "Joannis",
  		"profile": {
  		  "firstName": "Joannis",
  		  "lastName": "Orlandos"
  		}
  	},
  	{
  		"username": "Obbut",
  		"profile": {
  		  "firstName": "Robbert",
  		  "lastName": "Brandsma"
  		}
  	}
  ]
}
let obbutLastName = String(object["users"][1]["profile"]["lastName"]) // "Brandsma"

嵌套文档

复杂数组和大括号字面量可能会混淆Swift类型系统。如果发生这种情况,请显式地将其字面量指定为Document类型

var userDocument: Document = [
	"username": "Joannis",
	"online": true,
	"age": 20,
	"pi_constant": 3.14,
	"profile": [
		"firstName": "Joannis",
		"lastName": "Orlandos",
		"pets": [
			[
				"name": "Noodles",
				"type": "Parrot"
			] as Document,
			[
				"name": "Witje",
				"type": "Rabbit"
			]
		] as Document
	] as Document
]

Codable

文档可以从SwiftNIO的ByteBufferFoundation.Data中进行实例化。您可以使用.validate()函数手动验证此文档的格式。这还将指定数据损坏的位置。

如果您将DocumentPrimitive传递给BSONDecoder,如果格式匹配,您就可以解码任何Decodable类型。同样,BSONEncoder可以将您的Swift类型编码成Document

支持类型

所有非过时的BSON 1.1类型都受支持。

  • 双精度浮点数
  • 字符串
  • 文档
  • 数组
  • ObjectId
  • 布尔值
  • 日期时间
  • 32位整数
  • 64位整数
  • 空值
  • 二进制
  • 正则表达式
  • 最小键
  • 最大键
  • 时间戳
  • JavaScript代码
  • 具有作用域的JavaScript代码
  • Decimal128