swift使用swift-protobuf协议通讯,使用指北

2024-06-20 19:20

本文主要是介绍swift使用swift-protobuf协议通讯,使用指北,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

什么是Protobuf

Protobuf(Protocol Buffers)协议😉 Protobuf 是一种由 Google 开发的二进制序列化格式和相关的技术,它用于高效地序列化和反序列化结构化数据,通常用于网络通信、数据存储等场景。

为什么要使用Protobuf? 因为快

其实 Protobuf 在许多领域都得到了广泛应用,特别是在分布式系统、RPC(Remote Procedure Call)框架和数据存储中,它提供了一种高效、简洁和可扩展的方式来序列化和交换数据,

Protobuf 的主要优点包括:

高效性:Protobuf 序列化后的二进制数据通常比其他序列化格式(比如超级常用的JSON)更小,并且序列化和反序列化的速度更快,这对于性能敏感的应用非常有益。
简洁性:Protobuf 使用一种定义消息格式的语法,它允许定义字段类型、顺序和规则(消息结构更加清晰和简洁)
版本兼容性:Protobuf 支持向前和向后兼容的版本控制,使得在消息格式发生变化时可以更容易地处理不同版本的通信。
语言无关性:Protobuf 定义的消息格式可以在多种编程语言中使用,这有助于跨语言的通信和数据交换(截至本文发布目前官方支持的有C++/C#/Dart/Go/Java/Kotlin/python/Swift)
自动生成代码:Protobuf 通常与相应的工具一起使用,可以自动生成代码,包括序列化/反序列化代码和相关的类(减少了手动编写代码的工作量,提高效率)

安装编译器

注意:需要swift5.8以上的版本和xcode14.3以后的版本才可以

你也可以通过命令行使用 swift --version 命令来查看安装的Swift版本。这将会输出类似于下面的信息,显示当前安装的Swift编译器的版本:

安装swift-protobuf:这条命令将会给你的电脑上安装 protoc 和 Swift 代码生成器插件。

brew install swift-protobuf

根据官方文档可以使用brew安装:

安装完之后,输入protoc将会出现提示:

编译Proto文件

将.proto文件编译为swift代码:--swift_out=. 表示将生成的文件放在当前文件夹中

protoc --swift_out=. my.proto

运行之后,就会出现一个GameMsg.pb.swift文件,这就是编译后的swift文件:

生成的代码将为每个 proto 字段公开一个 Swift 属性以及一组序列化和反序列化功能。假如你的proto文件内容是:

syntax = "proto3";message BookInfo {int64 id = 1;string title = 2;string author = 3;
}

那么生成的swift代码:

// DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: game.proto
//
// For information on using the generated types, please see the documentation:
//   https://github.com/apple/swift-protobuf/import Foundation
import SwiftProtobuf// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}typealias Version = _2
}struct BookInfo {// SwiftProtobuf.Message conformance is added in an extension below. See the// `Message` and `Message+*Additions` files in the SwiftProtobuf library for// methods supported on all messages.var id: Int64 = 0var title: String = String()var author: String = String()var unknownFields = SwiftProtobuf.UnknownStorage()init() {}
}#if swift(>=5.5) && canImport(_Concurrency)
extension BookInfo: @unchecked Sendable {}
#endif  // swift(>=5.5) && canImport(_Concurrency)// MARK: - Code below here is support for the SwiftProtobuf runtime.extension BookInfo: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {static let protoMessageName: String = "BookInfo"static let _protobuf_nameMap: SwiftProtobuf._NameMap = [1: .same(proto: "id"),2: .same(proto: "title"),3: .same(proto: "author"),]mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {while let fieldNumber = try decoder.nextFieldNumber() {// The use of inline closures is to circumvent an issue where the compiler// allocates stack space for every case branch when no optimizations are// enabled. https://github.com/apple/swift-protobuf/issues/1034switch fieldNumber {case 1: try { try decoder.decodeSingularInt64Field(value: &self.id) }()case 2: try { try decoder.decodeSingularStringField(value: &self.title) }()case 3: try { try decoder.decodeSingularStringField(value: &self.author) }()default: break}}}func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {if self.id != 0 {try visitor.visitSingularInt64Field(value: self.id, fieldNumber: 1)}if !self.title.isEmpty {try visitor.visitSingularStringField(value: self.title, fieldNumber: 2)}if !self.author.isEmpty {try visitor.visitSingularStringField(value: self.author, fieldNumber: 3)}try unknownFields.traverse(visitor: &visitor)}static func ==(lhs: BookInfo, rhs: BookInfo) -> Bool {if lhs.id != rhs.id {return false}if lhs.title != rhs.title {return false}if lhs.author != rhs.author {return false}if lhs.unknownFields != rhs.unknownFields {return false}return true}
}

在项目中使用的话:

// 创建一个BookInfo对象,并给它赋值
var info = BookInfo()
info.id = 1734
info.title = "Really Interesting Book"
info.author = "Jane Smith"// 如上所述,但生成只读值:
let info2 = BookInfo.with {$0.id = 1735$0.title = "Even More Interesting"$0.author = "Jane Q. Smith"}// 序列化为二进制protobuf格式:可以选择序列化为
// 符合SwiftProtobufContiqueBytes的任何类型。例如
let binaryData: Data = try info.serializedBytes()
let binaryDataAsBytes: [UInt8] = try info.serializedBytes()// 从`binaryData反序列化接收到的Data对象`
let decodedInfo = try BookInfo(serializedData: binaryData)// 反序列化从`binaryDataAsBytes接收的[UInt8]对象`
let decodedInfo = try BookInfo(serializedBytes: binaryDataAsBytes)//序列化为JSON格式的数据对象,或符合
//SwiftProtobufContiqueBytes。例如
let jsonData: Data = try info.jsonUTF8Data()
let jsonBytes: [UInt8] = try info.jsonUTF8Bytes()// 从`jsonBytes从JSON格式反序列化`
let receivedFromJSON = try BookInfo(jsonUTF8Bytes: jsonBytes)

添加SwiftProtobuf到你的项目中

要想使用Protobuf还需要在你的项目中添加SwiftProtobuf,可以使用SPM添加或者使用CocoaPods添加,我这里习惯使用SPM,在xcode项目中可以直接右键添加包就可以了:

添加之后就可以在左侧项目的依赖包里面显示出来了:

解决遇到的问题

1.如果你在finder中在proto文件夹中生成swift代码,但是当你会到xcode总,发现proto文件夹中不一定会显示proto文件和生成的swift文件:

需要在xcode中手动添加文件到文件夹中:

再回到项目文件夹就可以看到了:

2.但是这个时候,当你打开生成的swift文件,可能发现报错了:

Could not find module 'SwiftProtobuf' for target 'arm64-apple-watchos'; found: arm64_32-apple-watchos, at: /Users/song/Library/Developer/Xcode/DerivedData/mywatch-coaeflxmpfflredurreogfyfvbxz/Index.noindex/Build/Products/Debug-watchos/SwiftProtobuf.swiftmodule 

这是因为你没有将 SwiftProtobuf 真正添加到项目中:

需要你手动再将依赖添加到项目中

就不会报错了:

简单的DEMO

我写了一个简单的Demo:

//
//  ContentView.swift
//  mywatch Watch App
//
//  Created by song on 2024/6/19.
//import SwiftUIstruct ContentView: View {// Create a BookInfo object and populate it:@State var info = BookInfo()// binaryData@State var binaryData: Data = .init()// binaryInfo@State var binaryInfo: BookInfo = .init()var body: some View {VStack {Text(info.author)Text("Hello, 1024小神!")Button(action: {info.id = 1734info.title = "Really Interesting Book"info.author = "Jane Smith"}, label: {Text("编辑")})Button(action: {binaryData = try! info.serializedData()print("二进制数据:\(binaryData)")}, label: {Text("序列化")})Button(action: {binaryInfo = try! BookInfo(serializedData: binaryData)print("反序列化数据:\(binaryInfo)")}, label: {Text("反序列化")})}.padding()}
}#Preview {ContentView()
}

 可以实现协议消息的序列化和反序列化:

这篇关于swift使用swift-protobuf协议通讯,使用指北的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1079027

相关文章

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

深入理解Go语言中二维切片的使用

《深入理解Go语言中二维切片的使用》本文深入讲解了Go语言中二维切片的概念与应用,用于表示矩阵、表格等二维数据结构,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录引言二维切片的基本概念定义创建二维切片二维切片的操作访问元素修改元素遍历二维切片二维切片的动态调整追加行动态

prometheus如何使用pushgateway监控网路丢包

《prometheus如何使用pushgateway监控网路丢包》:本文主要介绍prometheus如何使用pushgateway监控网路丢包问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录监控网路丢包脚本数据图表总结监控网路丢包脚本[root@gtcq-gt-monitor-prome

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected

C++ Log4cpp跨平台日志库的使用小结

《C++Log4cpp跨平台日志库的使用小结》Log4cpp是c++类库,本文详细介绍了C++日志库log4cpp的使用方法,及设置日志输出格式和优先级,具有一定的参考价值,感兴趣的可以了解一下... 目录一、介绍1. log4cpp的日志方式2.设置日志输出的格式3. 设置日志的输出优先级二、Window