This is an automated email from the ASF dual-hosted git repository. chaokunyang pushed a commit to branch main in repository https://gitbox.apache.org/repos/asf/fory-site.git
commit 289279974a1b569f8691e1cd8dbe9bb88767d626 Author: chaokunyang <[email protected]> AuthorDate: Mon Jul 27 05:33:11 2026 +0000 🔄 synced local 'docs/guide/' with remote 'docs/guide/' --- docs/guide/swift/basic-serialization.md | 84 +++++++-- docs/guide/swift/custom-serializers.md | 84 --------- docs/guide/swift/external-types.md | 292 ++++++++++++++++++++++++++++++ docs/guide/swift/index.md | 8 +- docs/guide/swift/manual-serializers.md | 308 ++++++++++++++++++++++++++++++++ docs/guide/swift/polymorphism.md | 159 +++++++++++++++-- docs/guide/swift/references.md | 6 +- docs/guide/swift/schema-evolution.md | 31 +++- docs/guide/swift/schema-metadata.md | 84 ++++++++- docs/guide/swift/troubleshooting.md | 35 +++- docs/guide/swift/type-registration.md | 37 +++- docs/guide/swift/xlang-serialization.md | 37 +++- 12 files changed, 1028 insertions(+), 137 deletions(-) diff --git a/docs/guide/swift/basic-serialization.md b/docs/guide/swift/basic-serialization.md index 7781f3c3c1..8446f977b4 100644 --- a/docs/guide/swift/basic-serialization.md +++ b/docs/guide/swift/basic-serialization.md @@ -47,8 +47,8 @@ struct Person: Equatable { } let fory = Fory() -fory.register(Address.self, id: 100) -fory.register(Person.self, id: 101) +try fory.register(Address.self, id: 100) +try fory.register(Person.self, id: 101) let person = Person( id: 42, @@ -78,6 +78,56 @@ let fromBuffer: Person = try fory.deserialize(from: inputBuffer) assert(fromBuffer == person) ``` +## Selecting a Serializer + +A type that implements `Serializer` with `Target == Self` selects itself: + +```swift +let data = try fory.serialize(person) +let decoded: Person = try fory.deserialize(data) +``` + +This implicit selection composes through generated fields and ordinary +optionals, arrays, sets, and dictionaries. It also applies when an application +intentionally gives an external type one retroactive self-target conformance. + +When a separate serializer targets the value, select it with `with`: + +```swift +try fory.register(UserSerializer.self, id: 200) + +let data = try fory.serialize( + externalUser, + with: UserSerializer.self +) +let decoded = try fory.deserialize( + data, + with: UserSerializer.self +) +``` + +The same selection works with existing buffers: + +```swift +var output = Data() +try fory.serialize( + externalUser, + with: UserSerializer.self, + to: &output +) + +let input = ByteBuffer(data: output) +let decoded = try fory.deserialize( + from: input, + with: UserSerializer.self +) +``` + +See [External-Type Serialization](external-types.md) for structural +serializers and recursive carrier roots. See +[Manual Serializers](manual-serializers.md) for serializers implemented +directly by a type, retroactive conformances, and separate manual serializers. + ## Built-in Supported Types ### Primitive and scalar @@ -101,18 +151,26 @@ supports epoch-day and `Date` conversions through `fromEpochDay(_:)`, ### Collections -- `[T]` where `T: Serializer` -- `Set<T>` where `T: Serializer & Hashable` -- `[K: V]` where `K: Serializer & Hashable`, `V: Serializer` -- Optional variants (`T?`) +- Optionals and arrays whose values directly implement `Serializer` +- Sets whose elements directly implement `Serializer` and are `Hashable` +- Dictionaries whose keys and values directly implement `Serializer`, with + `Hashable` keys + +Children that use a separate serializer compose with: + +- `OptionalSerializer<S>` +- `ArraySerializer<S>` +- `SetSerializer<S>` +- `DictionarySerializer<KS, VS>` ### Dynamic -- `Any` -- `AnyObject` -- `any Serializer` +- `Any` and `AnyObject` - `AnyHashable` -- `[Any]` -- `[String: Any]` -- `[Int32: Any]` -- `[AnyHashable: Any]` +- Arbitrary application protocol values +- Supported heterogeneous arrays and dictionaries + +`Any` and `AnyObject` roots use direct root APIs. Arbitrary application +protocol roots and dynamic values nested in carriers use explicit `with:` +selection. +See [Polymorphism and Dynamic Types](polymorphism.md). diff --git a/docs/guide/swift/custom-serializers.md b/docs/guide/swift/custom-serializers.md deleted file mode 100644 index 2ced166780..0000000000 --- a/docs/guide/swift/custom-serializers.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: Custom Serializers -sidebar_position: 9 -id: custom_serializers -license: | - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---- - -For types that cannot or should not use Fory model macros, implement `Serializer` manually. - -## When to Use Custom Serializers - -- External types with strict wire compatibility requirements -- Specialized compact encodings -- Existing payload adaptation paths -- Highly tuned hot-path serialization - -## Implementing `Serializer` - -```swift -import Foundation -import Fory - -struct UUIDBox: Serializer, Equatable { - var value: UUID = UUID(uuidString: "00000000-0000-0000-0000-000000000000")! - - static func foryDefault() -> UUIDBox { - UUIDBox() - } - - static var staticTypeId: ForyTypeId { - .ext - } - - func foryWriteData(_ context: WriteContext, hasGenerics: Bool) throws { - _ = hasGenerics - try value.uuidString.foryWriteData(context, hasGenerics: false) - } - - static func foryReadData(_ context: ReadContext) throws -> UUIDBox { - let raw = try String.foryReadData(context) - guard let uuid = UUID(uuidString: raw) else { - throw ForyError.invalidData("invalid UUID string: \(raw)") - } - return UUIDBox(value: uuid) - } -} -``` - -## Register and Use - -```swift -let fory = Fory() -fory.register(UUIDBox.self, id: 300) - -let input = UUIDBox(value: UUID()) -let data = try fory.serialize(input) -let output: UUIDBox = try fory.deserialize(data) - -assert(input == output) -``` - -## Choosing `staticTypeId` - -For manually implemented custom types, use `staticTypeId` that matches the wire kind you are implementing. - -Typical choices: - -- `.structType`: regular structured object -- `.enumType` / `.typedUnion`: enum-like values -- `.ext`: extension/custom kind diff --git a/docs/guide/swift/external-types.md b/docs/guide/swift/external-types.md new file mode 100644 index 0000000000..5307bf1f4a --- /dev/null +++ b/docs/guide/swift/external-types.md @@ -0,0 +1,292 @@ +--- +title: External-Type Serialization +sidebar_position: 9 +id: external_types +license: | + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--- + +External-type serialization lets an application serialize a type owned by +another Swift module without modifying that type. + +Use an external structural serializer when the target exposes a schema that +Fory can access and construct directly. Use a +[manual serializer](manual-serializers.md) when the target needs a customized +encoding or has private construction invariants. + +An external structural serializer is a separate declaration. Register it, then +select it explicitly at roots, fields, and carrier children. + +For one application-owned global implementation, Swift also permits an +external type to conform retroactively to `Serializer` with `Target == Self`. +That form uses ordinary implicit selection everywhere and has process-global +conformance risks. See [Manual Serializers](manual-serializers.md). + +## External Structs + +Declare a local serializer with the same serialized fields and select the +external target: + +```swift +import Fory +import ThirdParty + +@ForyStruct(target: ThirdParty.User.self) +struct UserSerializer { + var name: String + var age: UInt32 +} +``` + +Register and use the serializer: + +```swift +let fory = Fory() +try fory.register(UserSerializer.self, id: 100) + +let user = ThirdParty.User(name: "Alice", age: 32) +let bytes = try fory.serialize(user, with: UserSerializer.self) +let decoded = try fory.deserialize(bytes, with: UserSerializer.self) +``` + +The target struct must expose readable properties and an accessible initializer +whose labels and value types match the serializer declaration. A public +struct's synthesized memberwise initializer is not automatically public. + +## External Classes + +Use a class serializer declaration for a class target: + +```swift +@ForyStruct(target: ThirdParty.Node.self) +final class NodeSerializer { + var value: Int32 = 0 + + @ForyField(with: OptionalSerializer<NodeSerializer>.self) + var next: ThirdParty.Node? = nil +} +``` + +The target class must have an accessible zero-argument initializer and writable +serialized properties. These requirements allow Fory to preserve shared and +circular references. + +Use a manual serializer if the class is immutable, requires constructor +arguments, or cannot be safely observed before all fields are assigned. + +## External Enums + +Use `@ForyEnum(target:)` for an enum with no associated values: + +```swift +@ForyEnum(target: ThirdParty.Status.self) +enum StatusSerializer { + case active + case disabled +} +``` + +An enum from another module must be exhaustively switchable. A resilient +non-frozen public enum requires a manual serializer. + +## External Unions + +Use `@ForyUnion(target:)` for xlang union values: + +```swift +@ForyUnion(target: ThirdParty.Command<UnknownCase>.self) +enum CommandSerializer { + @ForyUnknownCase + case unknown(UnknownCase) + + @ForyCase(id: 0) + case rename(String) + + @ForyCase(id: 1, payload: .with(UserSerializer.self)) + case replace(ThirdParty.User) +} +``` + +The target must expose matching cases and a lossless +`unknown(UnknownCase)` case. A dependency-free third-party module can declare a +generic unknown payload, such as `Command<UnknownPayload>`, and the serializer +can target its `Command<UnknownCase>` specialization. Use a manual serializer +when a third-party union has a different unknown-case representation or cannot +preserve unknown payloads. + +A known Swift union case has zero or one associated value. Use an explicit +struct payload when an alternative has multiple logical fields. + +## Selecting a Serializer for a Field + +Select one exact field node with `@ForyField(with:)`: + +```swift +@ForyStruct +struct Account { + @ForyField(with: UserSerializer.self) + var owner: ThirdParty.User +} +``` + +For an optional field, select the optional carrier: + +```swift +@ForyField(with: OptionalSerializer<UserSerializer>.self) +var owner: ThirdParty.User? +``` + +The selected serializer's `Target` must exactly match the declared field type. + +## Selecting Serializers Inside Carriers + +Use `.with(...)` inside collection field annotations: + +```swift +@ForyStruct +struct Directory { + @ListField(element: .with(UserSerializer.self)) + var users: [ThirdParty.User] + + @SetField(element: .with(KeySerializer.self)) + var keys: Set<ThirdParty.Key> + + @MapField( + key: .with(KeySerializer.self), + value: .with(UserSerializer.self) + ) + var usersByKey: [ThirdParty.Key: ThirdParty.User] + + @MapField( + value: .list(element: .with(UserSerializer.self)) + ) + var groups: [String: [ThirdParty.User]] +} +``` + +Whole-carrier selection is equivalent: + +```swift +@ForyField(with: ArraySerializer<UserSerializer>.self) +var users: [ThirdParty.User] +``` + +At one field node, `with` cannot be combined with an encoding or another type +selection. It may be combined with `id`. + +## Root Carrier Composition + +Swift provides carrier serializers for its supported generic carriers: + +| Carrier serializer | Target | +| ------------------------------ | ------------------------ | +| `OptionalSerializer<S>` | `S.Target?` | +| `ArraySerializer<S>` | `[S.Target]` | +| `SetSerializer<S>` | `Set<S.Target>` | +| `DictionarySerializer<KS, VS>` | `[KS.Target: VS.Target]` | + +Carrier serializers compose recursively: + +```swift +typealias DirectorySerializer = DictionarySerializer< + String, + ArraySerializer<OptionalSerializer<UserSerializer>> +> + +let bytes = try fory.serialize( + directory, + with: DirectorySerializer.self +) + +let decoded = try fory.deserialize( + bytes, + with: DirectorySerializer.self +) +``` + +`SetSerializer` requires a hashable target element. +`DictionarySerializer` requires a hashable target key. + +Carrier serializers use the same optional, array, set, and dictionary +encodings as ordinary Swift values. + +## Buffer APIs + +The explicit serializer selection is available for all typed root forms: + +```swift +var output = Data() +try fory.serialize(user, with: UserSerializer.self, to: &output) + +let input = ByteBuffer(data: output) +let decoded = try fory.deserialize( + from: input, + with: UserSerializer.self +) +``` + +The `with` label always selects a serializer. + +## Dynamic Values + +Registered external targets work through dynamic `Any`, `AnyObject`, and +application protocol values: + +```swift +protocol Animal { + var name: String { get } +} + +let animal: any Animal = cat +let bytes = try fory.serialize( + animal, + with: DynamicSerializer<any Animal>.self +) +let decoded = try fory.deserialize( + bytes, + with: DynamicSerializer<any Animal>.self +) +``` + +Register each concrete target through its ordinary, external structural, or +manual serializer. + +For a root carrier containing protocol values, compose +`DynamicSerializer` explicitly: + +```swift +typealias AnimalArraySerializer = + ArraySerializer<DynamicSerializer<any Animal>> + +let bytes = try fory.serialize( + animals, + with: AnimalArraySerializer.self +) +``` + +## Type Aliases + +Serializer aliases and root carrier aliases are supported. + +When a field type alias hides a collection shape, supply the full recursive +field hint: + +```swift +typealias Users = [ThirdParty.User] + +@ForyField(type: .list(element: .with(UserSerializer.self))) +var users: Users +``` diff --git a/docs/guide/swift/index.md b/docs/guide/swift/index.md index 92dcb709e4..721864fc64 100644 --- a/docs/guide/swift/index.md +++ b/docs/guide/swift/index.md @@ -27,7 +27,8 @@ Apache Fory Swift provides high-performance object graph serialization with stro - `@ForyStruct`, `@ForyEnum`, and `@ForyUnion` macros for zero-boilerplate model serialization - Xlang protocol compatibility with Java, Rust, Go, Python, and more - Compatible mode for schema evolution across versions -- Built-in support for dynamic values (`Any`, `AnyObject`, `any Serializer`, `AnyHashable`) +- External structural, manual, and recursively composed carrier serializers +- Built-in support for dynamic values and arbitrary application protocol existentials - Reference tracking for shared/circular graphs, including weak references on classes ## Install @@ -55,7 +56,8 @@ targets: [ - [Xlang Serialization](xlang-serialization.md) - [Schema Metadata](schema-metadata.md) - [Type Registration](type-registration.md) -- [Custom Serializers](custom-serializers.md) +- [External-Type Serialization](external-types.md) +- [Manual Serializers](manual-serializers.md) - [Shared and Circular References](references.md) - [Polymorphism and Dynamic Types](polymorphism.md) - [Schema Evolution](schema-evolution.md) @@ -73,7 +75,7 @@ struct User: Equatable { } let fory = Fory() -fory.register(User.self, id: 1) +try fory.register(User.self, id: 1) let input = User(name: "alice", age: 30) let data = try fory.serialize(input) diff --git a/docs/guide/swift/manual-serializers.md b/docs/guide/swift/manual-serializers.md new file mode 100644 index 0000000000..0af5960fdc --- /dev/null +++ b/docs/guide/swift/manual-serializers.md @@ -0,0 +1,308 @@ +--- +title: Manual Serializers +sidebar_position: 10 +id: manual_serializers +license: | + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--- + +Use a manual serializer when a target needs a custom encoding or cannot meet +the direct-access requirements of an +[external structural serializer](external-types.md). + +A manual serializer is not limited to external types: + +- A target that itself conforms to `Serializer` with `Target == Self` selects + that implementation implicitly everywhere. +- A separate serializer whose `Target` is another type must be selected + explicitly everywhere it is needed. + +The same selection rules apply to roots, generated fields, optionals, arrays, +sets, and dictionaries. Register a separate serializer and select it explicitly +where it is used. + +## When to Use a Manual Serializer + +- The target has private or immutable state. +- The target must enforce construction invariants. +- The target needs a specialized compact encoding. +- The target needs custom validation or construction logic. +- An external enum is not exhaustively switchable. +- An external union cannot represent `UnknownCase`. + +## User-Owned Targets + +When you own the target, implement `Serializer` on the target itself and set +`Target` to the same type: + +```swift +import Fory + +struct AccountID: Serializer, Equatable { + typealias Target = AccountID + + let rawValue: UInt64 + + static var staticTypeId: TypeId { + .ext + } + + static func writeData( + _ value: AccountID, + _ context: WriteContext + ) throws { + try UInt64.writeData(value.rawValue, context) + } + + static func readData( + _ context: ReadContext + ) throws -> AccountID { + AccountID(rawValue: try UInt64.readData(context)) + } +} +``` + +Register and use the type through the ordinary root APIs: + +```swift +let fory = Fory() +try fory.register(AccountID.self, id: 300) + +let input = AccountID(rawValue: 42) +let data = try fory.serialize(input) +let output: AccountID = try fory.deserialize(data) + +assert(input == output) +``` + +No `with:` argument is needed because `AccountID.Target == AccountID`. + +## One Global Serializer for an External Type + +Swift permits an application to make an external type implement `Serializer` +through a retroactive conformance: + +```swift +import Foundation +import Fory + +extension UUID: @retroactive Serializer { + public typealias Target = UUID + + public static var staticTypeId: TypeId { + .ext + } + + public static func defaultValue( + _ context: ReadContext + ) throws -> UUID { + _ = context + return UUID( + uuidString: "00000000-0000-0000-0000-000000000000" + )! + } + + public static func writeData( + _ value: UUID, + _ context: WriteContext + ) throws { + try String.writeData(value.uuidString, context) + } + + public static func readData( + _ context: ReadContext + ) throws -> UUID { + let raw = try String.readData(context) + guard let uuid = UUID(uuidString: raw) else { + throw ForyError.invalidData("invalid UUID string: \(raw)") + } + return uuid + } +} +``` + +Register the external type itself: + +```swift +try fory.register(UUID.self, id: 300) + +let input = UUID() +let data = try fory.serialize(input) +let output: UUID = try fory.deserialize(data) +``` + +Because `UUID.Target == UUID`, unannotated generated fields and ordinary +carriers also select this implementation: + +```swift +@ForyStruct +struct Request { + var requestID: UUID +} + +let input = [UUID(), UUID()] +let data = try fory.serialize(input) +let output: [UUID] = try fory.deserialize(data) +``` + +A retroactive conformance applies to the entire process. Swift allows only one +`Serializer` conformance for a given type; `@retroactive` acknowledges the +compiler warning but does not make competing conformances safe. Use this form +only when the application intentionally chooses the single global +implementation. Public libraries should generally provide a separate +serializer instead. + +## Separate Serializers + +Use a separate serializer when a public library must not claim a process-global +conformance or when an application needs multiple or alternative +implementations. The target may be external or user-owned: + +```swift +import Foundation +import Fory + +public enum UUIDStringSerializer: Serializer { + public typealias Target = UUID + + public static var staticTypeId: TypeId { + .ext + } + + public static func defaultValue( + _ context: ReadContext + ) throws -> UUID { + _ = context + return UUID( + uuidString: "00000000-0000-0000-0000-000000000000" + )! + } + + public static func writeData( + _ value: UUID, + _ context: WriteContext + ) throws { + try String.writeData(value.uuidString, context) + } + + public static func readData( + _ context: ReadContext + ) throws -> UUID { + let raw = try String.readData(context) + guard let uuid = UUID(uuidString: raw) else { + throw ForyError.invalidData("invalid UUID string: \(raw)") + } + return uuid + } +} +``` + +Register the separate serializer and select it explicitly at the root: + +```swift +let fory = Fory() +try fory.register(UUIDStringSerializer.self, id: 300) + +let input = UUID() +let data = try fory.serialize(input, with: UUIDStringSerializer.self) +let output = try fory.deserialize(data, with: UUIDStringSerializer.self) + +assert(input == output) +``` + +Another declaration, such as `UUIDBytesSerializer`, may target the same type +with a different body. Fory cannot choose between separate serializers +automatically. Select the desired serializer with `with:` at roots and with the +matching field annotation. Register only one implementation for the target on +a given `Fory` instance. + +The direct `Any` and `AnyObject` root conveniences remain dynamic operations. +A registered serializer may be used for a concrete value passed as `Any`, but +typed roots and fields still require `with:` for a separate serializer. + +## Fields and Carriers + +A field whose type directly implements `Serializer` with `Target == Self` +needs no selector: + +```swift +@ForyStruct +struct Request { + var accountID: AccountID +} +``` + +A separate serializer must be selected explicitly: + +```swift +@ForyStruct +struct ExternalRequest { + @ForyField(with: UUIDStringSerializer.self) + var requestID: UUID +} +``` + +Ordinary carriers containing types that directly implement `Serializer` need +no selector. This includes intentional retroactive conformances: + +```swift +let accountIDs = [ + AccountID(rawValue: 1), + AccountID(rawValue: 2), +] +let data = try fory.serialize(accountIDs) +let output: [AccountID] = try fory.deserialize(data) +``` + +For an element that uses a separate serializer, name it in the carrier +annotation: + +```swift +@ListField(element: .with(UUIDStringSerializer.self)) +var requestIDs: [UUID] +``` + +At a root, use the matching carrier serializer: + +```swift +let data = try fory.serialize( + requestIDs, + with: ArraySerializer<UUIDStringSerializer>.self +) +``` + +## Manual Serializer Rules + +A manual serializer must return `.ext` from `staticTypeId`. The +`.structType`, `.enumType`, and `.typedUnion` values are reserved for +`@ForyStruct`, `@ForyEnum`, and `@ForyUnion`. + +`writeData` and `readData` process only the target body. Do not call a root +`serialize` or `deserialize` method from either operation. + +## Defaults + +Implement `defaultValue(_:)` only when the target has a valid value for a null +or missing field. + +## Input Validation + +Reject invalid input with an appropriate `ForyError`. + +## Manual Class Serializers + +For a cyclic class, override the complete-value `read` operation and use Fory's +reference APIs so repeated references resolve to the same object. diff --git a/docs/guide/swift/polymorphism.md b/docs/guide/swift/polymorphism.md index fa52427d30..4e4ba51d4d 100644 --- a/docs/guide/swift/polymorphism.md +++ b/docs/guide/swift/polymorphism.md @@ -19,9 +19,12 @@ license: | limitations under the License. --- -Fory Swift supports dynamic serialization for `Any`, `AnyObject`, and `any Serializer`. +Fory Swift supports dynamic serialization for `Any`, `AnyObject`, arbitrary +application protocol existentials, and supported heterogeneous collections. +`Any` and `AnyObject` roots use direct convenience APIs. Application protocols +and recursively composed carriers select `DynamicSerializer` explicitly. -## Top-level Dynamic APIs +## Dynamic Roots ```swift let fory = Fory() @@ -31,17 +34,142 @@ let data = try fory.serialize(dynamic) let decoded: Any = try fory.deserialize(data) ``` -Equivalent overloads exist for: +The equivalent explicit form is +`with: DynamicSerializer<Any>.self`. It is useful when composing serializers, +but is unnecessary for an `Any` root. `AnyObject` has the same direct root +APIs. -- `AnyObject` -- `any Serializer` -- `AnyHashable` -- `[Any]` -- `[String: Any]` -- `[Int32: Any]` -- `[AnyHashable: Any]` +A concrete external value passed as `Any` may use its registered serializer. +For typed roots and fields, select a separate serializer explicitly with +`with:`. -## Dynamic Fields in Fory Model Types +Heterogeneous containers compose carrier serializers: + +```swift +typealias AnyArraySerializer = + ArraySerializer<DynamicSerializer<Any>> + +typealias StringAnyMapSerializer = DictionarySerializer< + String, + DynamicSerializer<Any> +> +``` + +Use `DynamicSerializer<AnyHashable>` for an erased dynamic dictionary key. + +Use the exact heterogeneous shape for dynamic lists and maps: `[Any]`, +`[String: Any]`, `[Int32: Any]`, or `[AnyHashable: Any]`. For example, write +`["a", "b"] as [Any]` before storing that heterogeneous list in `Any`. +Keep homogeneous lists and maps in their ordinary concrete types. + +## Application Protocols + +Register each concrete target that may appear. No Fory-specific marker +protocol is required: + +```swift +protocol Animal { + var name: String { get } +} + +@ForyStruct +struct Dog: Animal { + var name: String = "" +} + +@ForyStruct(target: ThirdParty.Cat.self) +struct CatSerializer { + var name: String +} + +let fory = Fory() +try fory.register(Dog.self, id: 100) +try fory.register(CatSerializer.self, id: 101) + +let input: any Animal = Dog(name: "Rex") +let data = try fory.serialize( + input, + with: DynamicSerializer<any Animal>.self +) +let output = try fory.deserialize( + data, + with: DynamicSerializer<any Animal>.self +) +``` + +Every concrete target must conform to the requested application protocol. A +target that is unregistered or does not conform fails deserialization. + +## Protocol Fields + +Application protocol fields are dynamic: + +```swift +@ForyStruct +struct Zoo { + var featured: any Animal + var animals: [any Animal] +} +``` + +Register `Zoo` and every concrete target that may appear. + +Use an optional when the field needs a nil default: + +```swift +@ForyStruct +struct OptionalZoo { + var featured: (any Animal)? = nil +} +``` + +## Protocol Root Carriers + +Use `DynamicSerializer<T>` as the child of a root carrier: + +```swift +typealias AnimalArraySerializer = + ArraySerializer<DynamicSerializer<any Animal>> + +let data = try fory.serialize( + animals, + with: AnimalArraySerializer.self +) + +let decoded = try fory.deserialize( + data, + with: AnimalArraySerializer.self +) +``` + +Optional and map roots compose the same way: + +```swift +typealias FeaturedSerializer = + OptionalSerializer<DynamicSerializer<any Animal>> + +typealias AnimalMapSerializer = DictionarySerializer< + String, + DynamicSerializer<any Animal> +> +``` + +Swift's normal `Hashable` rules still apply to set elements and dictionary +keys. Use `AnyHashable` for erased dynamic keys. + +## Explicitly Polymorphic Class Nodes + +Select `DynamicSerializer<Base>` when a class-typed field must preserve its +concrete subclass: + +```swift +@ForyField(with: DynamicSerializer<AnimalBase>.self) +var animal: AnimalBase +``` + +Register every concrete subclass that may appear. + +## Dynamic `Any` Fields ```swift @ForyStruct @@ -66,15 +194,18 @@ struct Address { } let fory = Fory() -fory.register(Address.self, id: 100) +try fory.register(Address.self, id: 100) ``` ## Null Semantics - `Any` null representation: `ForyAnyNullValue` - `AnyObject` null representation: `NSNull` +- `AnyHashable` dynamic null-key representation: + `AnyHashable(ForyAnyNullValue())` - Optional dynamic values map to the corresponding null representation on decode -## Current Limitations +## `AnyHashable` Keys -- `AnyHashable` keys must wrap values that are both `Hashable` and supported by Fory dynamic serialization +`AnyHashable` keys must wrap values that are both `Hashable` and supported by +Fory dynamic serialization. diff --git a/docs/guide/swift/references.md b/docs/guide/swift/references.md index aef7f72435..8d889857ec 100644 --- a/docs/guide/swift/references.md +++ b/docs/guide/swift/references.md @@ -59,8 +59,8 @@ final class AnimalPair { } let fory = Fory(ref: true) -fory.register(Animal.self, id: 200) -fory.register(AnimalPair.self, id: 201) +try fory.register(Animal.self, id: 200) +try fory.register(AnimalPair.self, id: 201) let shared = Animal(name: "cat") let input = AnimalPair(first: shared, second: shared) @@ -93,7 +93,7 @@ final class Node { } let fory = Fory(ref: true) -fory.register(Node.self, id: 300) +try fory.register(Node.self, id: 300) let node = Node(value: 7) node.next = node diff --git a/docs/guide/swift/schema-evolution.md b/docs/guide/swift/schema-evolution.md index ed22293d74..4efe61c8f6 100644 --- a/docs/guide/swift/schema-evolution.md +++ b/docs/guide/swift/schema-evolution.md @@ -59,10 +59,10 @@ struct PersonV2 { } let writer = Fory() -writer.register(PersonV1.self, id: 1) +try writer.register(PersonV1.self, id: 1) let reader = Fory() -reader.register(PersonV2.self, id: 1) +try reader.register(PersonV2.self, id: 1) let v1 = PersonV1(name: "alice", age: 30, address: "main st") let bytes = try writer.serialize(v1) @@ -73,6 +73,33 @@ assert(v2.age == 30) assert(v2.phone == nil) ``` +## External Targets + +An external structural serializer declaration defines the local schema used +for compatibility: + +```swift +@ForyStruct(target: ThirdParty.User.self) +struct UserV2Serializer { + var name: String + var age: Int32 + var phone: String? +} +``` + +Register the serializer with the same logical ID or name used by the peer, then +select it at the root: + +```swift +try reader.register(UserV2Serializer.self, id: 1) +let user = try reader.deserialize( + bytes, + with: UserV2Serializer.self +) +``` + +The serializer declaration name does not affect the wire schema. + ## What Is Safe in Compatible Mode - Add new fields diff --git a/docs/guide/swift/schema-metadata.md b/docs/guide/swift/schema-metadata.md index 32b8801593..71be73ffee 100644 --- a/docs/guide/swift/schema-metadata.md +++ b/docs/guide/swift/schema-metadata.md @@ -23,12 +23,59 @@ This page covers macro-level schema metadata in Swift. ## Available Macro Attributes -- `@ForyStruct` on struct/class models -- `@ForyEnum` on C-style enum models -- `@ForyUnion` and `@ForyCase` on associated-value enum models +- `@ForyStruct` on struct/class models and external structural serializers +- `@ForyEnum` on C-style enum models and external enum serializers +- `@ForyUnion` and `@ForyCase` on associated-value enum models and external union serializers - `@ForyField(encoding: ...)` on numeric fields +- `@ForyField(with: ...)` for exact serializer selection - `@ListField`, `@ArrayField`, `@SetField`, and `@MapField` for collection field metadata +## External Targets + +Use `target:` when the serializer declaration and serialized value type are +different: + +```swift +@ForyStruct(target: ThirdParty.User.self) +struct UserSerializer { + var name: String + var age: UInt32 +} +``` + +Equivalent target arguments are available on `@ForyEnum` and `@ForyUnion`. +See [External-Type Serialization](external-types.md) for target access and +construction requirements. + +## `@ForyField(with:)` + +An unannotated field implicitly selects its declared type when that type +implements `Serializer` with `Target == Self`, including an intentional +retroactive external conformance. Use `with` to select a separate serializer +for one exact field node: + +```swift +@ForyStruct +struct Account { + @ForyField(with: UserSerializer.self) + var owner: ThirdParty.User +} +``` + +The serializer target must exactly match the declared field type. Optional and +whole-carrier nodes select their carrier serializer explicitly: + +```swift +@ForyField(with: OptionalSerializer<UserSerializer>.self) +var owner: ThirdParty.User? + +@ForyField(with: ArraySerializer<UserSerializer>.self) +var users: [ThirdParty.User] +``` + +`with` may be combined with `id`, but not with `encoding`, `type`, or another +type selection at the same node. + ## `@ForyField(encoding:)` Use `@ForyField` to override integer encoding strategy. @@ -80,6 +127,15 @@ struct NestedMetrics: Equatable { @MapField(value: .list(element: .encoding(.fixed))) var groups: [String: [Int32?]] = [:] + + @ListField(element: .with(UserSerializer.self)) + var users: [ThirdParty.User] = [] + + @MapField( + key: .with(KeySerializer.self), + value: .list(element: .with(UserSerializer.self)) + ) + var usersByKey: [ThirdParty.Key: [ThirdParty.User]] = [:] } ``` @@ -119,12 +175,22 @@ enum Event { } ``` +External payloads select a serializer with `.with(...)`: + +```swift +@ForyCase(id: 2, payload: .with(UserSerializer.self)) +case user(ThirdParty.User) +``` + Every `@ForyUnion` must declare `@ForyUnknownCase case unknown(UnknownCase)` and at least one non-`unknown` case. The unknown case is only the Fory-owned forward-compatibility carrier and cannot be the default value source. It is omitted from the schema case table because the marker only selects the carrier and does not add a schema entry. Schema cases use non-negative IDs. +A known union case has zero or one associated value. Use a struct payload when +one alternative contains multiple logical fields. + ## Model Macro Requirements ### Struct and class fields @@ -147,17 +213,21 @@ final class Node { } ``` +An external class serializer uses a class declaration. Its target must expose +an accessible zero-argument initializer and writable matching fields so Fory +can preserve shared and circular references. + ## Dynamic Any Fields in Macro Types Fory model macros support dynamic fields and nested containers: -- `Any`, `AnyObject`, `any Serializer` +- `Any`, `AnyObject`, and arbitrary `any Protocol` existentials - `AnyHashable` - `[Any]` - `[String: Any]` - `[Int32: Any]` - `[AnyHashable: Any]` -Current limitations: - -- `Dictionary<K, Any>` is only supported when `K` is `String`, `Int32`, or `AnyHashable` +Other dictionary key types work when the key is `Hashable` and implements +`Serializer` with `Target == Self`. For an external key using a separate +serializer, select it with `@MapField(key: .with(KeySerializer.self))`. diff --git a/docs/guide/swift/troubleshooting.md b/docs/guide/swift/troubleshooting.md index b08818c698..990b52cb6c 100644 --- a/docs/guide/swift/troubleshooting.md +++ b/docs/guide/swift/troubleshooting.md @@ -25,12 +25,19 @@ This page covers common Swift issues and how to debug them. ### `Type not registered: ...` -Cause: user type was not registered on the current `Fory` instance. +Cause: the selected user serializer was not registered on the current `Fory` +instance. Fix: ```swift -fory.register(MyType.self, id: 100) +try fory.register(MyType.self, id: 100) +``` + +For an external target, register its serializer: + +```swift +try fory.register(UserSerializer.self, id: 100) ``` ### `Type mismatch: expected ..., got ...` @@ -69,13 +76,29 @@ Add explicit type annotations to stored properties. Remove default values from enum case associated values. -### `Set<...> with Any elements is not supported by @ForyStruct yet` +### Selected serializer target does not match the field type + +The serializer selected by `with` must target the exact field node. Select the +matching carrier for optional or collection fields: + +```swift +@ForyField(with: OptionalSerializer<UserSerializer>.self) +var user: ThirdParty.User? +``` + +### External target construction errors + +An external struct needs readable matching properties and an accessible +matching initializer. An external class needs an accessible zero-argument +initializer and writable matching properties. -Use `[Any]` or a typed set instead. +Use a [manual serializer](manual-serializers.md) when the target does not expose +that construction surface. -### `Dictionary<..., ...> with Any values is only supported for String, Int32, or AnyHashable keys` +### Union case has multiple associated values -Switch key type to `String`, `Int32`, or `AnyHashable`, or avoid dynamic `Any` map values. +Swift uses the xlang union format, whose known cases contain zero or one value. +Move multiple logical fields into an explicit `@ForyStruct` payload. ## Debugging Commands diff --git a/docs/guide/swift/type-registration.md b/docs/guide/swift/type-registration.md index 696d87f62a..2246b38e14 100644 --- a/docs/guide/swift/type-registration.md +++ b/docs/guide/swift/type-registration.md @@ -23,7 +23,8 @@ This page covers registration APIs for user-defined types. ## Why Registration Is Required -User types (`struct`, `class`, enum/union, ext types) must be registered before serialization/deserialization. +Register user-defined structs, classes, enums, unions, and external targets +before serialization or deserialization. If a type is missing, deserialization fails with: @@ -41,9 +42,32 @@ struct User { } let fory = Fory() -fory.register(User.self, id: 1) +try fory.register(User.self, id: 1) ``` +For an external structural serializer, register the separate serializer +declaration: + +```swift +@ForyStruct(target: ThirdParty.User.self) +struct UserSerializer { + var name: String + var age: UInt32 +} + +try fory.register(UserSerializer.self, id: 1) +``` + +If an application intentionally gives an external type one retroactive +`Serializer` conformance with `Target == Self`, register the target itself: + +```swift +try fory.register(UUID.self, id: 2) +``` + +After registering a separate serializer, select it explicitly at each root, +field, or carrier child where it is required. + ## Register by Name ### Fully-qualified name @@ -66,7 +90,14 @@ Keep registration mapping consistent across peers: - ID mode: same type uses same numeric ID on all peers - Name mode: same type uses same namespace and type name on all peers - Do not mix ID and name mapping for the same logical type across services +- Register only one serializer for each target type on a `Fory` instance + +Registration closes after the first root serialization or deserialization. +Complete all registrations before the first root operation. ## Dynamic Types and Registration -When serializing dynamic values (`Any`, `AnyObject`, `any Serializer`) that contain user-defined types, the concrete types must still be registered. +When serializing `Any`, `AnyObject`, or application protocol values, register +each concrete target through its ordinary, external structural, or manual +serializer. `Any` and `AnyObject` use direct root APIs; application protocols +select `DynamicSerializer<T>` explicitly. diff --git a/docs/guide/swift/xlang-serialization.md b/docs/guide/swift/xlang-serialization.md index f60c8423d6..f2e20a6dd1 100644 --- a/docs/guide/swift/xlang-serialization.md +++ b/docs/guide/swift/xlang-serialization.md @@ -39,7 +39,7 @@ struct Order { } let fory = Fory() -fory.register(Order.self, id: 100) +try fory.register(Order.self, id: 100) ``` ### Name-based registration @@ -52,7 +52,11 @@ try fory.register(Order.self, name: "com.example.Order") - Keep type registration mapping consistent across languages - Keep compatible mode enabled when independently evolving schemas. Swift enables it by default. -- Register all user-defined concrete types used by dynamic fields (`Any`, `any Serializer`) +- Register all user-defined concrete targets used by dynamic fields and + application protocol values +- Use an external structural serializer, a separate manual serializer, or one + intentional retroactive self-target conformance for a type owned by another + module ## Lists and Dense Arrays @@ -77,6 +81,35 @@ numeric data. | `array<float32>` | `@ArrayField(element: .float32) var values: [Float]` | | `array<float64>` | `@ArrayField(element: .float64) var values: [Double]` | +An array that uses a separate element serializer still uses normal list +encoding. Use `@ArrayField` only for supported dense bool or numeric arrays. + +## External Targets + +External structural serializers produce the same xlang STRUCT, ENUM, or UNION +schema and value bytes as an equivalent ordinary Swift model: + +```swift +@ForyStruct(target: ThirdParty.Order.self) +struct OrderSerializer { + var id: Int64 + var amount: Double +} + +try fory.register(OrderSerializer.self, id: 100) +``` + +Use `.with(...)` in field metadata and `with:` at a root. See +[External-Type Serialization](external-types.md). + +That explicit selection is required because the structural serializer is a +separate declaration. An external type with one intentional retroactive +`Target == Self` conformance instead uses ordinary roots, fields, and carriers. + +Swift has no native serialization mode. A known `@ForyUnion` case has zero or +one associated value. Use a struct payload for a union alternative with +multiple logical fields. + ## Swift IDL Workflow Generate Swift models directly from Fory IDL/Proto/FBS inputs: --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
