### Example: JSON Deserialization Setup Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/serialization.md Demonstrates setting up JSONDeserializationOptions and a JSONDeserializer, then deserializing JSON data using a person descriptor. Requires a TypeRegistry. ```swift let registry = TypeRegistry() let options = JSONDeserializationOptions( ignoreUnknownFields: true, strictTypeValidation: true, typeRegistry: registry, maxNestingDepth: 64 ) let deserializer = JSONDeserializer(options: options) let person = try await deserializer.deserialize(jsonData, using: personDescriptor) ``` -------------------------------- ### Clone and Navigate to Examples Directory Source: https://github.com/truewebber/swift-protoreflect/blob/master/README.md Clone the repository and navigate to the examples directory to run the provided demonstrations. ```bash git clone https://github.com/truewebber/swift-protoreflect.git cd swift-protoreflect/examples ``` -------------------------------- ### Run Basic SwiftProtoReflect Examples Source: https://github.com/truewebber/swift-protoreflect/blob/master/README.md Execute basic examples demonstrating library functionality such as 'HelloWorld', 'FieldTypes', and 'TimestampDemo'. ```bash # Basic examples swift run HelloWorld swift run FieldTypes swift run TimestampDemo ``` -------------------------------- ### Run Proto3 Compliance Examples Source: https://github.com/truewebber/swift-protoreflect/blob/master/README.md Run examples that demonstrate Proto3 compliance features like Syntax and Defaults, Optional Presence, Unknown Fields, and Canonical JSON. ```bash # Proto3 compliance swift run SyntaxAndDefaults swift run OptionalPresence swift run UnknownFields swift run JsonCanonical ``` -------------------------------- ### Create and Populate FileDescriptor Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/descriptor.md Example demonstrating the creation of a FileDescriptor and adding a MessageDescriptor with fields to it. ```swift var file = FileDescriptor(name: "person.proto", package: "example", syntax: "proto3") var personMsg = MessageDescriptor(name: "Person") personMsg.addField(FieldDescriptor(name: "id", number: 1, type: .int32)) personMsg.addField(FieldDescriptor(name: "name", number: 2, type: .string)) file.addMessage(personMsg) ``` -------------------------------- ### Swift JSON Deserialization Example Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/configuration.md Demonstrates creating `JSONDeserializationOptions` and initializing a `JSONDeserializer` for parsing JSON data. ```swift let registry = TypeRegistry() try await registry.registerFile(fileDescriptor) let options = JSONDeserializationOptions( ignoreUnknownFields: true, // skip extra fields strictTypeValidation: true, // enforce types typeRegistry: registry, maxNestingDepth: 64 ) let deserializer = JSONDeserializer(options: options) let message = try await deserializer.deserialize(jsonData, using: descriptor) ``` -------------------------------- ### SwiftProtobuf Serialization Source: https://github.com/truewebber/swift-protoreflect/blob/master/MIGRATION_GUIDE.md Example of serializing a message to binary and JSON, and deserializing it back using SwiftProtobuf. ```swift let data = try person.serializedData() let json = try person.jsonUTF8Data() let decoded = try Person(serializedBytes: data) ``` -------------------------------- ### SwiftProtobuf Message Creation Source: https://github.com/truewebber/swift-protoreflect/blob/master/MIGRATION_GUIDE.md Example of creating a message instance using SwiftProtobuf's generated code. ```swift import GeneratedProtos var person = Person() person.name = "Alice" person.age = 30 person.email = "alice@example.com" ``` -------------------------------- ### DynamicMessage Example Usage Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/dynamic-message.md Demonstrates creating a message descriptor, instantiating a DynamicMessage, setting and adding values to fields, and retrieving values. ```swift import SwiftProtoReflect // Define message structure var personMsg = MessageDescriptor(name: "Person", fullName: "Person") personMsg.addField(FieldDescriptor(name: "id", number: 1, type: .int32)) personMsg.addField(FieldDescriptor(name: "name", number: 2, type: .string)) personMsg.addField(FieldDescriptor(name: "emails", number: 3, type: .string, isRepeated: true)) // Create and populate a message var person = DynamicMessage(descriptor: personMsg) try person.set(Int32(123), forField: "id") try person.set("Alice", forField: "name") try person.addRepeatedValue("alice@example.com", forField: "emails") try person.addRepeatedValue("alice.work@example.com", forField: "emails") // Read values let name = try person.get(forField: "name") as? String let hasEmail = try person.hasValue(forField: "emails") ``` -------------------------------- ### SwiftProtoReflect Message Creation Source: https://github.com/truewebber/swift-protoreflect/blob/master/MIGRATION_GUIDE.md Example of creating a dynamic message instance using SwiftProtoReflect at runtime. ```swift import SwiftProtoReflect var desc = MessageDescriptor(name: "Person", fullName: "example.Person") desc.addField(FieldDescriptor(name: "name", number: 1, type: .string)) desc.addField(FieldDescriptor(name: "age", number: 2, type: .int32)) desc.addField(FieldDescriptor(name: "email", number: 3, type: .string)) var person = DynamicMessage(descriptor: desc) try person.set("Alice", forField: "name") try person.set(Int32(30), forField: "age") try person.set("alice@example.com", forField: "email") ``` -------------------------------- ### DescriptorPool Example Usage Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/registry.md Demonstrates initializing a DescriptorPool, adding a file descriptor, finding a message descriptor, creating a dynamic message, and retrieving all message type names. ```swift let pool = DescriptorPool(includeBuiltinDescriptors: true) // Add a file descriptor try await pool.addFileDescriptor(myFile) // Find a message descriptor if let msgDesc = await pool.findMessageDescriptor(named: "example.Person") { // Create a message from it if let msg = await pool.createMessage(forType: "example.Person") { print("Created message: \(msg.descriptor.name)") } } // Get all message type names let allTypes = await pool.allMessageTypeNames() ``` -------------------------------- ### TypeRegistry Usage Example Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/registry.md Demonstrates common TypeRegistry operations including initialization, registering files and messages, looking up types, checking existence, and retrieving all messages. ```swift let registry = TypeRegistry() // Register a file try await registry.registerFile(personFile) // Register a message directly try await registry.registerMessage(personMessage) // Lookup types if let msg = await registry.findMessage(named: "example.Person") { print("Found: \(msg.fullName)") } // Check if type exists let hasType = await registry.hasMessage(named: "example.Address") // Get all messages let allMessages = await registry.allMessages() ``` -------------------------------- ### DescriptorBridge Usage Example Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/bridge.md Demonstrates converting message descriptors between SwiftProtoReflect and SwiftProtobuf formats using `DescriptorBridge`. ```swift let bridge = DescriptorBridge() // Convert from SwiftProtoReflect to SwiftProtobuf let swiftProtoDescriptor = try bridge.toProtobufDescriptor(from: myMessageDescriptor) // Convert from SwiftProtobuf to SwiftProtoReflect let reflectDescriptor = try bridge.fromProtobufDescriptor(swiftProtoDescriptor) ``` -------------------------------- ### DescriptorOption Usage Examples Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/types.md Shows how to use DescriptorOption when setting options for fields and messages. Options are provided as a dictionary mapping option names to their DescriptorOption values. ```swift let field = FieldDescriptor( name: "deprecated", number: 1, type: .bool, options: ["deprecated": .bool(true)] ) let msgOptions = ["java_package": .string("com.example")] let msg = MessageDescriptor(name: "Person", fullName: "Person", options: msgOptions) ``` -------------------------------- ### Example Usage of StaticMessageBridge Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/bridge.md Demonstrates a typical workflow for converting between static and dynamic messages using the StaticMessageBridge and its convenience extensions. Includes conversion in both directions. ```swift let bridge = StaticMessageBridge() // Static to Dynamic let staticPerson = Person.with { $0.name = "Alice" $0.id = 42 } let dynamicPerson = try bridge.toDynamicMessage(from: staticPerson) // Dynamic to Static (using convenience extension) let backToStatic: Person = try dynamicPerson.toStaticMessage(as: Person.self) // Or using the bridge directly let backToStatic2 = try bridge.toStaticMessage(from: dynamicPerson, as: Person.self) ``` -------------------------------- ### Dynamic Message Factory Example Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/dynamic-message.md Demonstrates the usage of `MessageFactory` to create empty messages, messages with initial field values, and to clone existing messages. ```swift let factory = MessageFactory() // Create empty message let msg1 = factory.createMessage(from: personDescriptor) // Create with field values let msg2 = try factory.createMessage( from: personDescriptor, with: ["id": Int32(42), "name": "John"] ) // Clone a message let msg3 = try factory.clone(msg2) ``` -------------------------------- ### SwiftProtoReflect Static-Dynamic Interop Source: https://github.com/truewebber/swift-protoreflect/blob/master/MIGRATION_GUIDE.md Example of converting between generated SwiftProtobuf messages and SwiftProtoReflect's DynamicMessage. ```swift let bridge = StaticMessageBridge() // Static → Dynamic let dynamic = try bridge.toDynamicMessage(from: staticPerson, using: personDesc) // Dynamic → Static let static: Person = try bridge.toStaticMessage(from: dynamic, as: Person.self) // Shorthand extensions let dynamic = try staticPerson.toDynamicMessage(using: personDesc) let static: Person = try dynamic.toStaticMessage(as: Person.self) ``` -------------------------------- ### Example Usage of Well-Known Type Extensions Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/well-known-types.md Demonstrates how to use the convenience extensions to create a timestamp and a Struct message from Swift types, and then convert them back to their native Swift representations. ```swift // Create a timestamp for now let timestamp = try DynamicMessage.timestampMessage(from: Date()) // Create a Struct from Swift dictionary let struct = try DynamicMessage.structMessage(from: ["key": "value"]) // Convert back to native types let date = try timestamp.toDate() let dict = try struct.toStructDictionary() ``` -------------------------------- ### SwiftProtoReflect Serialization Source: https://github.com/truewebber/swift-protoreflect/blob/master/MIGRATION_GUIDE.md Example of serializing a dynamic message to binary and JSON, and deserializing it back using SwiftProtoReflect. ```swift let registry = TypeRegistry() try registry.registerMessage(desc) let data = try BinarySerializer().serialize(person) let json = try JSONSerializer(options: .init(typeRegistry: registry)).serialize(person) let decoded = try BinaryDeserializer(options: .init(typeRegistry: registry)) .deserialize(data, using: desc) ``` -------------------------------- ### Work with Protobuf Well-Known Types Source: https://github.com/truewebber/swift-protoreflect/blob/master/README.md Examples of using well-known types like Timestamps and Structs, and type erasure with the Any message type. ```swift // Timestamps let timestampMessage = try DynamicMessage.timestampMessage(from: Date()) let backToDate = try timestampMessage.toDate() // JSON-like structures let data: [String: Any] = ["user": "john", "active": true] let structMessage = try DynamicMessage.structMessage(from: data) // Type erasure let anyMessage = try message.packIntoAny() let unpackedMessage = try await anyMessage.unpackFromAny(to: personSchema) ``` -------------------------------- ### ValueFieldInfo Initialization Examples Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/types.md Illustrates initializing ValueFieldInfo for different map value types. The 'typeName' parameter is mandatory for message and enum types. ```swift // String → string map ValueFieldInfo(name: "value", number: 2, type: .string) // String → Address message map ValueFieldInfo(name: "value", number: 2, type: .message, typeName: "example.Address") ``` -------------------------------- ### Example Usage of WellKnownTypesRegistry Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/well-known-types.md Demonstrates how to use the shared registry instance to create specialized objects and register custom handlers. It shows converting a timestamp message and then creating an instance using a custom handler for 'my.Type'. ```swift // Use shared registry let timestamp = try await WellKnownTypesRegistry.shared.createSpecialized( from: timestampMessage, typeName: WellKnownTypeNames.timestamp ) // Register custom handler struct MyCustomHandler: WellKnownTypeHandler { static let handledTypeName = "my.Type" static let supportPhase = WellKnownSupportPhase.advanced // ... implement protocol methods } await WellKnownTypesRegistry.shared.register(MyCustomHandler.self) // Create instance with custom handler let custom = try await WellKnownTypesRegistry.shared.createSpecialized( from: customMessage, typeName: "my.Type" ) ``` -------------------------------- ### Swift JSON Serialization Example Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/configuration.md Configures and uses `JSONSerializer` with various options including type registration, pretty printing, and default value handling. ```swift let registry = TypeRegistry() try await registry.registerFile(fileDescriptor) let options = JSONSerializationOptions( useOriginalFieldNames: false, // camelCase prettyPrinted: true, // readable includeDefaultValues: false, // omit defaults useCanonicalWellKnownTypeEncoding: true, escapeSlashesInStrings: true, sortJSONObjectKeys: false, typeRegistry: registry ) let serializer = JSONSerializer(options: options) let jsonData = try await serializer.serialize(message) let jsonString = String(data: jsonData, encoding: .utf8)! print(jsonString) ``` -------------------------------- ### Initialize ExtensionRange Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/descriptor.md Creates a descriptor for an extension range, specifying the start (inclusive) and end (exclusive) field numbers. This is a proto2 feature. ```swift public init(start: Int, end: Int) ``` -------------------------------- ### SwiftProtoReflect Well-Known Types Source: https://github.com/truewebber/swift-protoreflect/blob/master/MIGRATION_GUIDE.md Example of creating and converting well-known Protobuf types using SwiftProtoReflect's dynamic message utilities. ```swift let ts = try DynamicMessage.timestampMessage(from: Date()) let date = try ts.toDate() let dur = try DynamicMessage.durationMessage(from: TimeInterval(3.5)) let empty = try DynamicMessage.emptyMessage() let mask = try DynamicMessage.fieldMaskMessage(from: ["name", "email"]) let structMsg = try DynamicMessage.structMessage(from: ["key": "value", "count": 42]) ``` -------------------------------- ### Get Syntax Version of Type Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/registry.md Returns the syntax version ('proto2' or 'proto3') of a registered type by its full name. ```swift func syntaxForType(_ fullName: String) -> String? ``` -------------------------------- ### SwiftProtobuf Well-Known Types Source: https://github.com/truewebber/swift-protoreflect/blob/master/MIGRATION_GUIDE.md Example of using SwiftProtobuf's generated types for well-known Protobuf types like Timestamp. ```swift let ts = Google_Protobuf_Timestamp(date: Date()) ``` -------------------------------- ### Create Field Descriptors Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/descriptor.md Examples of initializing FieldDescriptor instances for various field types including scalar, repeated, nested message, and map fields. Pay attention to the parameters used for `isRepeated` and `isMap`, and the structure for `mapEntryInfo`. ```swift // Simple scalar field let nameField = FieldDescriptor( name: "name", number: 2, type: .string ) // Repeated field (array) let emailsField = FieldDescriptor( name: "emails", number: 3, type: .string, isRepeated: true ) // Nested message field let addressField = FieldDescriptor( name: "address", number: 4, type: .message, typeName: "example.Address" ) // Map field let tagsField = FieldDescriptor( name: "tags", number: 5, type: .message, isMap: true, mapEntryInfo: MapEntryInfo( keyFieldInfo: KeyFieldInfo(name: "key", number: 1, type: .string), valueFieldInfo: ValueFieldInfo(name: "value", number: 2, type: .string) ) ) ``` -------------------------------- ### Create Oneof Group and Add Fields Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/descriptor.md Example showing the creation of a OneofDescriptor and associating fields with it within a MessageDescriptor. The 'oneofIndex' property on FieldDescriptor is crucial for linking fields to the oneof group. ```swift var contact = OneofDescriptor(name: "contact", index: 0) var msg = MessageDescriptor(name: "Person", fullName: "example.Person") msg.addField(FieldDescriptor( name: "email", number: 3, type: .string, oneofIndex: 0 )) msg.addField(FieldDescriptor( name: "phone", number: 4, type: .string, oneofIndex: 0 )) msg.addOneofDecl(contact) ``` -------------------------------- ### Example: Modifying Message Fields Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/dynamic-message.md Demonstrates creating a message, using a mutable accessor to set string and int32 fields, and then obtaining the updated message. It shows a nested conditional check for successful updates. ```swift var msg = factory.createMessage(from: descriptor) var accessor = msg.mutableFieldAccessor() if accessor.setString("Alice", forField: "name") { if accessor.setInt32(30, forField: "age") { msg = accessor.updatedMessage() } } ``` -------------------------------- ### Example: Accessing Field Values Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/dynamic-message.md Demonstrates how to use FieldAccessor to get string, int32, and string array values from a DynamicMessage. It checks if the value was successfully retrieved before printing. ```swift let accessor = FieldAccessor(person) if let name = accessor.getString("name") { print("Name: \(name)") } if let age = accessor.getInt32("age") { print("Age: \(age)") } if let emails = accessor.getStringArray("emails") { print("Emails: \(emails)") } ``` -------------------------------- ### Create and Add Service Methods Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/descriptor.md Shows how to initialize a ServiceDescriptor and add MethodDescriptors to it, defining RPC methods for a gRPC service. ```swift var userService = ServiceDescriptor(name: "UserService", fullName: "example.UserService") userService.addMethod( ServiceDescriptor.MethodDescriptor( name: "GetUser", inputType: "example.GetUserRequest", outputType: "example.User" ) ) userService.addMethod( ServiceDescriptor.MethodDescriptor( name: "ListUsers", inputType: "example.Empty", outputType: "example.User", serverStreaming: true ) ) ``` -------------------------------- ### Create and Add Enum Values Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/descriptor.md Demonstrates how to create an EnumDescriptor and add enum values to it. Includes validation for proto3 syntax. ```swift var statusEnum = EnumDescriptor(name: "Status", fullName: "example.Status") statusEnum.addValue(EnumDescriptor.EnumValue(name: "UNKNOWN", number: 0)) statusEnum.addValue(EnumDescriptor.EnumValue(name: "ACTIVE", number: 1)) statusEnum.addValue(EnumDescriptor.EnumValue(name: "INACTIVE", number: 2)) // Validate for proto3 let errors = statusEnum.validateProto3() ``` -------------------------------- ### SwiftProtoReflect Registering Nested Types Source: https://github.com/truewebber/swift-protoreflect/blob/master/MIGRATION_GUIDE.md Example of registering nested or cross-file types in SwiftProtoReflect's TypeRegistry. ```swift let registry = TypeRegistry() try registry.registerFile(addressFile) try registry.registerFile(personFile) // Or use the convenience initializer: let registry = try TypeRegistry(fileDescriptors: [addressFile, personFile]) ``` -------------------------------- ### OneofDescriptor Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/descriptor.md Represents a oneof group within a Protocol Buffers message, including its initializer, properties, and an example of its usage. ```APIDOC ## OneofDescriptor Represents a oneof group in a Protocol Buffers message. ### Initializer ```swift public init(name: String, index: Int, options: [String: DescriptorOption] = [:]) ``` Creates a oneof group descriptor. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | name | String | Yes | — | Group name (e.g., "contact") | | index | Int | Yes | — | Zero-based index within parent message | | options | [String: DescriptorOption] | No | [:] | Oneof options | ### Properties | Property | Type | Description | |----------|------|-------------| | name | String | Group name | | index | Int | Zero-based index (matches FieldDescriptor.oneofIndex) | | options | [String: DescriptorOption] | Oneof options | ### Example ```swift var contact = OneofDescriptor(name: "contact", index: 0) var msg = MessageDescriptor(name: "Person", fullName: "example.Person") msg.addField(FieldDescriptor( name: "email", number: 3, type: .string, oneofIndex: 0 )) msg.addField(FieldDescriptor( name: "phone", number: 4, type: .string, oneofIndex: 0 )) msg.addOneofDecl(contact) ``` ``` -------------------------------- ### SwiftProtobuf Field Access Source: https://github.com/truewebber/swift-protoreflect/blob/master/MIGRATION_GUIDE.md Example of accessing message fields using SwiftProtobuf's compile-time safe properties. ```swift let name = person.name // String, compile-time safe let age = person.age // Int32 ``` -------------------------------- ### Create FileDescriptor Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/configuration.md Initialize a FileDescriptor with its name, package, syntax, and optional dependencies and file-level options. This is used for schema definition. ```swift let file = FileDescriptor( name: "person.proto", package: "example", dependencies: ["google/protobuf/timestamp.proto"], syntax: "proto3", options: [:] ) ``` -------------------------------- ### SwiftProtoReflect Field Access Source: https://github.com/truewebber/swift-protoreflect/blob/master/MIGRATION_GUIDE.md Example of accessing dynamic message fields using SwiftProtoReflect, with type casting or typed accessors. ```swift let name = try person.get(forField: "name") as? String let age = try person.get(forField: "age") as? Int32 // Or via typed accessor: let accessor = person.fieldAccessor let name = accessor.getString("name") let age = accessor.getInt32("age") ``` -------------------------------- ### Get Fully Qualified Type Name Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/descriptor.md Retrieves the fully-qualified name for a type within a specific file, formatted as 'package.typeName'. ```swift func getFullName(for typeName: String) -> String ``` -------------------------------- ### Initialize BinarySerializer Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/serialization.md Initializes a BinarySerializer with optional serialization options. Defaults to standard options. ```swift public init(options: SerializationOptions = SerializationOptions()) ``` -------------------------------- ### Get Updated Message Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/dynamic-message.md Retrieves the DynamicMessage after all mutations have been applied by the MutableFieldAccessor. This returns a new message instance reflecting the changes. ```swift func updatedMessage() -> DynamicMessage ``` -------------------------------- ### MapEntryInfo Initialization Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/types.md Shows how to initialize MapEntryInfo with KeyFieldInfo and ValueFieldInfo to describe map fields. This is used when defining fields that are maps. ```swift let mapField = FieldDescriptor( name: "tags", number: 5, type: .message, isMap: true, mapEntryInfo: MapEntryInfo( keyFieldInfo: KeyFieldInfo(name: "key", number: 1, type: .string), valueFieldInfo: ValueFieldInfo(name: "value", number: 2, type: .string) ) ) ``` -------------------------------- ### Get Field Type Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/dynamic-message.md Retrieve the declared FieldType for a given field by its name or number. Returns nil if the field is not found. ```swift func getFieldType(_ fieldName: String) -> FieldType? func getFieldType(_ fieldNumber: Int) -> FieldType? ``` -------------------------------- ### Using WellKnownTypeNames Constants Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/well-known-types.md Demonstrates how to use the predefined constants for checking message names or type names against well-known types. ```swift let isTimestamp = messageName == WellKnownTypeNames.timestamp if WellKnownTypeNames.allTypes.contains(typeName) { // Handle as well-known type } ``` -------------------------------- ### Get Registered Well-Known Types Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/well-known-types.md Returns a set containing the names of all well-known types for which handlers are currently registered in the registry. ```swift func getRegisteredTypes() -> Set ``` -------------------------------- ### Create MessageDescriptor Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/configuration.md Initialize a MessageDescriptor with its name, full name, syntax, and options. Alternatively, derive the full name from its parent FileDescriptor. ```swift // Form 1: explicit full name var msg1 = MessageDescriptor( name: "Person", fullName: "example.Person", syntax: "proto3", options: ["java_package": .string("com.example")] ) // Form 2: parent-derived full name let file = FileDescriptor(name: "person.proto", package: "example") var msg2 = MessageDescriptor(name: "Person", parent: file) // Result: fullName = "example.Person" ``` -------------------------------- ### Initialize TypeRegistry with FileDescriptors Source: https://github.com/truewebber/swift-protoreflect/blob/master/Sources/SwiftProtoReflect/Registry/_README.md Use this convenience initializer when you have all your proto file descriptors available. It automatically registers all messages, enums, and services defined within these descriptors. ```swift import SwiftProtobuf import SwiftProtoReflect // Build FileDescriptors for all proto files your application uses. var userFile = FileDescriptor(name: "user.proto", package: "myapp") userFile.addMessage(userDescriptor) userFile.addEnum(statusEnum) var orderFile = FileDescriptor(name: "order.proto", package: "myapp") orderFile.addMessage(orderDescriptor) // Convenience init — registers everything in one call. let registry = TypeRegistry(fileDescriptors: [userFile, orderFile]) // Pass to serializers/deserializers. let serializer = JSONSerializer(options: .init(typeRegistry: registry)) ``` -------------------------------- ### FileDescriptor Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/descriptor.md Represents a Protocol Buffers .proto file and all its contents, including its name, package, dependencies, syntax, and options. ```APIDOC ## FileDescriptor Represents a Protocol Buffers .proto file and all its contents. ### Initializer ```swift public init( name: String, package: String, dependencies: [String] = [], syntax: String = "proto3", options: [String: DescriptorOption] = [:], ) ``` | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | name | String | Yes | — | File name (e.g., "person.proto") | | package | String | Yes | — | Package name (e.g., "example.person") | | dependencies | [String] | No | [] | Imported .proto file names | | syntax | String | No | "proto3" | Proto syntax version | | options | [String: DescriptorOption] | No | [:] | File-level options | ``` -------------------------------- ### FileDescriptor Constructor Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/configuration.md Creates a FileDescriptor with its name, package, dependencies, syntax, and options. ```APIDOC ## FileDescriptor Constructor File descriptor creation with package, syntax, and dependencies. **Used by:** Schema definition ```swift public init( name: String, package: String, dependencies: [String] = [], syntax: String = "proto3", options: [String: DescriptorOption] = [:] ) ``` | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | name | String | — | File name (e.g., "person.proto") | | package | String | — | Package name (e.g., "example.person") | | dependencies | [String] | [] | Imported .proto file names | | syntax | String | "proto3" | Proto syntax version | | options | [String: DescriptorOption] | [:] | File-level options | ### Example ```swift let file = FileDescriptor( name: "person.proto", package: "example", dependencies: ["google/protobuf/timestamp.proto"], syntax: "proto3", options: [:] ) ``` **Source:** `Sources/SwiftProtoReflect/Public/Descriptor.swift:1195-1217` ``` -------------------------------- ### Dynamically Create and Populate a Protobuf Message Source: https://github.com/truewebber/swift-protoreflect/blob/master/README.md Define a message schema at runtime and then create and populate an instance of that message. Serialization to binary or JSON requires a TypeRegistry. ```swift import SwiftProtoReflect // Define a message schema at runtime var personSchema = MessageDescriptor(name: "Person", fullName: "Person") personSchema.addField(FieldDescriptor(name: "name", number: 1, type: .string)) personSchema.addField(FieldDescriptor(name: "age", number: 2, type: .int32)) personSchema.addField(FieldDescriptor(name: "emails", number: 3, type: .string, isRepeated: true)) // Create and populate a message var message = MessageFactory().createMessage(from: personSchema) try message.set("Alice", forField: "name") try message.set(Int32(25), forField: "age") try message.set(["alice@example.com"], forField: "emails") // Serialize to binary or JSON // TypeRegistry is required for JSONSerializer and deserializers; empty registry is fine for scalar-only messages. let registry = TypeRegistry() let binaryData = try BinarySerializer().serialize(message) let jsonData = try await JSONSerializer(options: .init(typeRegistry: registry)).serialize(message) ``` -------------------------------- ### Create TypeRegistry Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/configuration.md Initialize a TypeRegistry. An empty registry can be created directly, or it can be pre-populated with FileDescriptors, which may throw errors for duplicate files or types. ```swift // Empty registry let registry1 = TypeRegistry() // Pre-populated registry let registry2 = try await TypeRegistry(fileDescriptors: [file1, file2]) ``` -------------------------------- ### Get Field Values from Dynamic Message Source: https://github.com/truewebber/swift-protoreflect/blob/master/docs/ARCHITECTURE.md Retrieves field values from a dynamic message by field name. Requires type casting to the expected type. ```swift // Getting field values let name = try message.get(forField: "name") as? String let age = try message.get(forField: "age") as? Int32 ``` -------------------------------- ### Get WellKnownTypeHandler Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/well-known-types.md Retrieves the registered handler type for a given well-known type name. Returns nil if no handler is currently registered for the specified type. ```swift func getHandler(for typeName: String) -> WellKnownTypeHandler.Type? ``` -------------------------------- ### SerializationOptions Struct Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/types.md Configuration options for binary serialization. ```APIDOC ## Struct: SerializationOptions ### Description Binary serialization configuration. ### Properties - `usePackedRepeated`: Bool - Default: `true`. Pack repeated numeric fields for smaller encoding. ### Initializer - `init(usePackedRepeated: Bool = true)`: Initializes SerializationOptions. ``` -------------------------------- ### Create DescriptorPool Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/configuration.md Initialize a DescriptorPool. It can optionally include built-in descriptors for standard protobuf types, which is recommended for most use cases. ```swift // With built-in descriptors (recommended) let pool1 = DescriptorPool(includeBuiltinDescriptors: true) // Without built-in descriptors (minimal setup) let pool2 = DescriptorPool(includeBuiltinDescriptors: false) ``` -------------------------------- ### TypeRegistry Initializers Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/registry.md Initializes a TypeRegistry, either empty or pre-populated with file descriptors. ```APIDOC ## TypeRegistry Initializers ### `public init()` Creates an empty registry. ### `public init(fileDescriptors: [FileDescriptor]) async throws` Creates a registry pre-populated with types from file descriptors. #### Parameters - **fileDescriptors** ([FileDescriptor]): Required - File descriptors to register **Throws:** `RegistryError.duplicateFile` or `RegistryError.duplicateType` ``` -------------------------------- ### JSON Field Naming Examples Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/configuration.md Illustrates how JSON field names are represented based on the 'useOriginalFieldNames' option in JSONSerializationOptions. Default is camelCase, setting it to true uses snake_case. ```json { "firstName": "Alice", "lastName": "Smith" } ``` ```json { "first_name": "Alice", "last_name": "Smith" } ``` -------------------------------- ### Create TypeRegistry with File Descriptors Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/registry.md Initializes a TypeRegistry pre-populated with types from provided file descriptors. This is useful for setting up the registry with a known set of schemas. ```swift public init(fileDescriptors: [FileDescriptor]) async throws ``` -------------------------------- ### Convenience Extension: StaticMessage to DynamicMessage Auto Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/bridge.md Provides a convenience method on static SwiftProtobuf messages to convert them to DynamicMessage, automatically generating the descriptor. This offers a quick way to get a dynamic representation. ```swift extension SwiftProtobuf.Message { func toDynamicMessage() throws -> DynamicMessage } ``` -------------------------------- ### TypeRegistry Constructor Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/configuration.md Initializes a TypeRegistry, optionally pre-populating it with a list of FileDescriptors. ```APIDOC ## TypeRegistry Constructor Registry creation with optional pre-population. **Used by:** Type management ```swift public init() public init(fileDescriptors: [FileDescriptor]) async throws ``` | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | fileDescriptors (form 2) | [FileDescriptor] | Yes | Files to register on initialization | ### Throws - `RegistryError.duplicateFile`: Same filename appears twice - `RegistryError.duplicateType`: Same type fullName appears in multiple files ### Example ```swift // Empty registry let registry1 = TypeRegistry() // Pre-populated registry let registry2 = try await TypeRegistry(fileDescriptors: [file1, file2]) ``` **Source:** `Sources/SwiftProtoReflect/Public/Registry.swift:101-131` ``` -------------------------------- ### Convert Between Static and Dynamic Messages Source: https://github.com/truewebber/swift-protoreflect/blob/master/docs/ARCHITECTURE.md Demonstrates converting a dynamic message to a static Swift Protobuf message and vice versa. This is crucial for seamless interoperability between dynamic and static codebases. ```swift // Converting between static and dynamic let staticMessage: Person = try message.toStaticMessage(as: Person.self) let dynamicFromStatic = try staticPerson.toDynamicMessage() ``` -------------------------------- ### FieldDescriptor Initialization Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/types.md Demonstrates initializing FieldDescriptor instances with various types, including repeated and nested fields. Use FieldType to specify the field's data type. ```swift let field = FieldDescriptor(name: "age", number: 1, type: .int32) let repeated = FieldDescriptor(name: "emails", number: 2, type: .string, isRepeated: true) let nested = FieldDescriptor(name: "address", number: 3, type: .message, typeName: "Address") ``` -------------------------------- ### MessageDescriptor and FieldDescriptor Usage Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/descriptor.md Demonstrates how to define a message descriptor with fields and nested enums, and then create a dynamic message instance. ```APIDOC ## MessageDescriptor and FieldDescriptor Usage ### Description This example shows the creation of a `MessageDescriptor` for a `Person` message, including its fields (`id`, `name`, `email`) and a nested enum `Status`. It then utilizes `MessageFactory` to instantiate a dynamic message from this descriptor and set field values. ### Code Example ```swift import SwiftProtoReflect // Define a message descriptor var personMsg = MessageDescriptor(name: "Person", fullName: "example.Person") // Add fields personMsg.addField(FieldDescriptor(name: "id", number: 1, type: .int32)) personMsg.addField(FieldDescriptor(name: "name", number: 2, type: .string)) personMsg.addField(FieldDescriptor(name: "email", number: 3, type: .string)) // Define a nested enum var statusEnum = EnumDescriptor(name: "Status", fullName: "example.Person.Status") statusEnum.addValue(EnumDescriptor.EnumValue(name: "ACTIVE", number: 0)) statusEnum.addValue(EnumDescriptor.EnumValue(name: "INACTIVE", number: 1)) personMsg.addNestedEnum(statusEnum) // Create a dynamic message from the descriptor let factory = MessageFactory() var person = factory.createMessage(from: personMsg) try person.set("john", forField: "name") try person.set(Int32(42), forField: "id") ``` **Source:** `Sources/SwiftProtoReflect/Public/Descriptor.swift` ``` -------------------------------- ### Create DescriptorPool Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/registry.md Initializes a DescriptorPool for dynamic descriptor management. Optionally includes built-in descriptors for standard types. ```swift public init(includeBuiltinDescriptors: Bool = true) ``` -------------------------------- ### Create DescriptorBridge Instance Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/bridge.md Initializes a new `DescriptorBridge` to perform descriptor conversions. ```swift public init() ``` -------------------------------- ### DeserializationOptions Struct Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/types.md Configuration options for binary deserialization. ```APIDOC ## Struct: DeserializationOptions ### Description Binary deserialization configuration. ### Properties - `preserveUnknownFields`: Bool - Default: `true`. Keep fields not in descriptor. - `strictUTF8Validation`: Bool - Default: `true`. Validate string UTF-8 encoding. - `typeRegistry`: TypeRegistry - Required. Resolve nested message types. ### Initializer - `init(preserveUnknownFields: Bool = true, strictUTF8Validation: Bool = true, typeRegistry: TypeRegistry)`: Initializes DeserializationOptions. ``` -------------------------------- ### Working with Well-Known Types in Swift Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/README.md Demonstrates creating and converting well-known Protobuf types like Timestamp and Struct using DynamicMessage. Ensure you have imported the necessary types. ```swift // Create a Timestamp for the current time let timestamp = try DynamicMessage.timestampMessage(from: Date()) // Create a Struct from a Swift dictionary let struct = try DynamicMessage.structMessage(from: ["key": "value"]) // Convert back to native Swift types let date = try timestamp.toDate() let dict = try struct.toStructDictionary() ``` -------------------------------- ### Initialize JSON Deserializer Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/serialization.md Create a JSONDeserializer instance with specified JSON deserialization options. This initializer requires a JSONDeserializationOptions object. ```swift public init(options: JSONDeserializationOptions) ``` -------------------------------- ### SwiftProtoReflect v5 to v6: Descriptor Initializers Source: https://github.com/truewebber/swift-protoreflect/blob/master/MIGRATION_GUIDE.md Illustrates the removal of deprecated `parent: Any?` overloads for descriptor initializers in SwiftProtoReflect v6, requiring typed `DescriptorParent`. ```swift // v5 (removed) let msg = MessageDescriptor(name: "Child", parent: fileDesc as Any?) let enm = EnumDescriptor(name: "Status", parent: fileDesc as Any?) // v6 let msg = MessageDescriptor(name: "Child", parent: fileDesc) let enm = EnumDescriptor(name: "Status", parent: fileDesc) ``` -------------------------------- ### DescriptorPool Initializer Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/registry.md Initializes a DescriptorPool for dynamic descriptor management. ```APIDOC ## DescriptorPool Initializer ### `public init(includeBuiltinDescriptors: Bool = true)` Creates a new descriptor pool. #### Parameters - **includeBuiltinDescriptors** (Bool): Default `true` - Include built-in descriptors for standard types ``` -------------------------------- ### WellKnownTypesRegistry Singleton Instance Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/well-known-types.md Provides a process-wide singleton instance of WellKnownTypesRegistry, pre-populated with all built-in handlers. This is the primary way to access registry functionality. ```swift public static let shared = WellKnownTypesRegistry() ``` -------------------------------- ### Define and Create a Dynamic Message Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/descriptor.md This snippet demonstrates how to define a message structure with fields and a nested enum using SwiftProtoReflect's descriptor classes. It then shows how to create a dynamic message instance from this descriptor and set field values. ```swift import SwiftProtoReflect // Define a message descriptor var personMsg = MessageDescriptor(name: "Person", fullName: "example.Person") // Add fields personMsg.addField(FieldDescriptor(name: "id", number: 1, type: .int32)) personMsg.addField(FieldDescriptor(name: "name", number: 2, type: .string)) personMsg.addField(FieldDescriptor(name: "email", number: 3, type: .string)) // Define a nested enum var statusEnum = EnumDescriptor(name: "Status", fullName: "example.Person.Status") statusEnum.addValue(EnumDescriptor.EnumValue(name: "ACTIVE", number: 0)) statusEnum.addValue(EnumDescriptor.EnumValue(name: "INACTIVE", number: 1)) personMsg.addNestedEnum(statusEnum) // Create a dynamic message from the descriptor let factory = MessageFactory() var person = factory.createMessage(from: personMsg) try person.set("john", forField: "name") try person.set(Int32(42), forField: "id") ``` -------------------------------- ### Convenience Extensions Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/bridge.md Convenience methods added to DynamicMessage and SwiftProtobuf.Message for easier conversion. ```APIDOC ## Convenience Extensions ### Description SwiftProtoReflect adds convenience methods directly to message types for easier conversions. ### Extensions #### DynamicMessage Extension ```swift extension DynamicMessage { func toStaticMessage(as messageType: T.Type) throws -> T } ``` #### SwiftProtobuf.Message Extension ```swift extension SwiftProtobuf.Message { func toDynamicMessage(using descriptor: MessageDescriptor) throws -> DynamicMessage func toDynamicMessage() throws -> DynamicMessage } ``` ``` -------------------------------- ### Breaking: TypeRegistry, DescriptorPool, WellKnownTypesRegistry as Actors (v5 vs v6) Source: https://github.com/truewebber/swift-protoreflect/blob/master/MIGRATION_GUIDE.md Illustrates the change of `TypeRegistry`, `DescriptorPool`, and `WellKnownTypesRegistry` from classes to actors, requiring `await` for method calls in v6. ```swift // v5 let registry = TypeRegistry() try registry.registerMessage(desc) let found = registry.findMessage(named: "pkg.Msg") // v6 let registry = TypeRegistry() try await registry.registerMessage(desc) let found = await registry.findMessage(named: "pkg.Msg") ``` ```swift // v5 let pool = DescriptorPool() try pool.addFileDescriptor(file) let msg = pool.findMessageDescriptor(named: "pkg.Msg") // v6 let pool = DescriptorPool() try await pool.addFileDescriptor(file) let msg = await pool.findMessageDescriptor(named: "pkg.Msg") ``` ```swift // v5 let handler = WellKnownTypesRegistry.shared.getHandler(for: "google.protobuf.Timestamp") // v6 let handler = await WellKnownTypesRegistry.shared.getHandler(for: "google.protobuf.Timestamp") ``` -------------------------------- ### Breaking: Serializer Methods Become Async (v5 vs v6) Source: https://github.com/truewebber/swift-protoreflect/blob/master/MIGRATION_GUIDE.md Demonstrates how `JSONSerializer`, `JSONDeserializer`, and `BinaryDeserializer` methods become `async throws` in v6 due to their interaction with `TypeRegistry` as an actor. ```swift // v5 let data = try jsonSerializer.serialize(message) let msg = try jsonDeserializer.deserialize(jsonData, using: desc) let msg = try binaryDeserializer.deserialize(binData, using: desc) // v6 let data = try await jsonSerializer.serialize(message) let msg = try await jsonDeserializer.deserialize(jsonData, using: desc) let msg = try await binaryDeserializer.deserialize(binData, using: desc) ``` -------------------------------- ### Any Message Pack/Unpack Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/well-known-types.md Methods for packing and unpacking messages into/from the 'Any' well-known type. ```APIDOC ### Pack/unpack Any messages #### `func packIntoAny() throws -> DynamicMessage` Packs the current DynamicMessage into an 'Any' type message. #### `func unpackFromAny(to descriptor: MessageDescriptor) async throws -> DynamicMessage` Unpacks a message from an 'Any' type message using the provided `MessageDescriptor`. ``` -------------------------------- ### DynamicMessage Initialization Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/dynamic-message.md Creates an empty dynamic message from a descriptor. The descriptor defines the message's structure. ```swift public init(descriptor: MessageDescriptor) ``` -------------------------------- ### Discovery Methods Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/registry.md Returns arrays of all known type names. ```APIDOC ## allMessageTypeNames ### Description Returns an array of all known message type names. ### Method func ### Response #### Success Response - **[String]** - An array of message type names. ``` ```APIDOC ## allEnumTypeNames ### Description Returns an array of all known enum type names. ### Method func ### Response #### Success Response - **[String]** - An array of enum type names. ``` ```APIDOC ## allServiceNames ### Description Returns an array of all known service names. ### Method func ### Response #### Success Response - **[String]** - An array of service names. ``` ```APIDOC ## allFileNames ### Description Returns an array of all known file names. ### Method func ### Response #### Success Response - **[String]** - An array of file names. ``` -------------------------------- ### Convert File Descriptors Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/bridge.md Converts file descriptors between SwiftProtoReflect and SwiftProtobuf formats. ```swift func toProtobufFileDescriptor(from fileDescriptor: FileDescriptor) throws -> Google_Protobuf_FileDescriptorProto ``` ```swift func fromProtobufFileDescriptor(_ protobufDescriptor: Google_Protobuf_FileDescriptorProto) throws -> FileDescriptor ``` -------------------------------- ### DescriptorPool Constructor Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/configuration.md Creates a DescriptorPool, with an option to include standard protobuf descriptors. ```APIDOC ## DescriptorPool Constructor Descriptor pool creation with optional builtin descriptors. **Used by:** Dynamic descriptor creation ```swift public init(includeBuiltinDescriptors: Bool = true) ``` | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | includeBuiltinDescriptors | Bool | true | Pre-load descriptors for standard protobuf types (Timestamp, Duration, etc.) | ### Example ```swift // With built-in descriptors (recommended) let pool1 = DescriptorPool(includeBuiltinDescriptors: true) // Without built-in descriptors (minimal setup) let pool2 = DescriptorPool(includeBuiltinDescriptors: false) ``` **Source:** `Sources/SwiftProtoReflect/Public/Registry.swift:364-369` ``` -------------------------------- ### Creating Nested Descriptors Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/types.md Demonstrates how to create nested message and enum descriptors using a parent descriptor. Child descriptors automatically compute their full names. ```swift let file = FileDescriptor(name: "person.proto", package: "example", syntax: "proto3") // Child message automatically computes fullName from parent let address = MessageDescriptor(name: "Address", parent: file) // Result: fullName = "example.Address" // Nested enum let status = EnumDescriptor(name: "Status", parent: address) // Result: fullName = "example.Address.Status" ``` -------------------------------- ### BinarySerializer Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/serialization.md Serializes dynamic messages to binary Protocol Buffers wire format. ```APIDOC ## BinarySerializer Serializes dynamic messages to binary Protocol Buffers wire format. ### Initializer ```swift public init(options: SerializationOptions = SerializationOptions()) ``` #### Parameters - **options** (SerializationOptions) - Optional - Serialization options ### Methods #### serialize ```swift func serialize(_ message: DynamicMessage) throws -> Data ``` Serializes a dynamic message to binary format. ##### Parameters - **message** (DynamicMessage) - Message to serialize ##### Returns Binary data in Protocol Buffers wire format ##### Throws `SerializationError` if serialization failed ### Example ```swift let serializer = BinarySerializer() let data = try serializer.serialize(person) // data is ready to send or save ``` ``` -------------------------------- ### Removed: Deprecated Bridge Methods (v5 vs v6) Source: https://github.com/truewebber/swift-protoreflect/blob/master/MIGRATION_GUIDE.md Compares the syntax for using `DescriptorBridge.fromProtobufDescriptor` and `fromProtobufEnumDescriptor` between v5 and v6, highlighting the removal of optional parent types. ```swift // v5 (removed) let msg = try bridge.fromProtobufDescriptor(proto, parent: fileDesc as FileDescriptor?) let enm = try bridge.fromProtobufEnumDescriptor(proto, parent: fileDesc as Any?) // v6 let msg = try bridge.fromProtobufDescriptor(proto, parent: fileDesc) let enm = try bridge.fromProtobufEnumDescriptor(proto, parent: fileDesc) ``` -------------------------------- ### Initialize JSONSerializer Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/api-reference/serialization.md Initializes a JSONSerializer with required JSON serialization options. These options control aspects like field name formatting and pretty-printing. ```swift public init(options: JSONSerializationOptions) ``` -------------------------------- ### Create and Populate Dynamic Message Source: https://github.com/truewebber/swift-protoreflect/blob/master/_autodocs/README.md Defines a message schema and then creates and populates a dynamic message instance using a MessageFactory. Fields can be set by name and type. ```swift import SwiftProtoReflect // Define a message schema var personMsg = MessageDescriptor(name: "Person", fullName: "example.Person") personMsg.addField(FieldDescriptor(name: "id", number: 1, type: .int32)) personMsg.addField(FieldDescriptor(name: "name", number: 2, type: .string)) personMsg.addField(FieldDescriptor(name: "emails", number: 3, type: .string, isRepeated: true)) // Create and populate a message let factory = MessageFactory() var person = factory.createMessage(from: personMsg) try person.set(Int32(42), forField: "id") try person.set("Alice", forField: "name") try person.addRepeatedValue("alice@example.com", forField: "emails") // Access fields let accessor = FieldAccessor(person) if let name = accessor.getString("name") { print("Name: \(name)") } ```