Swift Protocols Concise Overview
2024, Jan 03
A handy, summarized guide talking about common protocols used in “Swift Standard Library” without going into too much details ~
Basic Behaviours
- Compare/Sort/Uniqueness: Comparable , Identifiable , Hashable
- Enumeration: CaseIterable, RawRepresentable
- String Representation: CustomStringConvertible for supporting
.description
property of class. Use CustomDebugStringConvertible for providing.debugDescription
for supportingString(reflecting:)
Serialization
- Codable (which includes both Encodable and Decodable), CodingUserInfoKey(Structure) is used to indicate the key specification in the custom Coding process. Both string and int types are supported.
- Customized serialization solution can be implemented via applying: KeyedEncoding/DecodingContainerProtocol and UnkeyedEncoding/DecodingContainer protocols
- Protocols for providing convenience literal initializations: e.g. ExpressibleByArrayLiteral, ExpressibleByUnicodeLiteral
Numbers & Basic Types
- Provides a list of common protocols that Numeric needs to follow: Numeric Protocols
- Basic arithmetic operations: AdditiveArithmetic (Support addition), Numeric (Support multiplication), SingedNumeric (Support negation, take negative), Strideable (Subtraction support)
- Integer arithmetic: BinaryInteger (Supports Bit operations and Clamping/Extending operations), FixedWithInteger (Support overflow calculation protection) SignedInteger /UnsignedInteger supports the division of larger values than the current type.
- Floating-point arithmetic: FloatingPoint (Floating-point Basic operation) BinaryFloatingPoint (Based on Floating Point, it further provides Floating-Point binary operation and exposes the calculation attributes related to significand, exponent and binad).
- Because the floating point itself has a limited range of expression, it cannot be accurately expressed for numbers at infinite positions after the decimal point, so use floatingPointClassification further description of the type of floating point: infinite/positive zero/negative zero/finite, etc.
- Use floatingPointSign express floating-point sign
- Use floatingPointRoundingRule declare round rules
- SIMD (Single Instruction Multi Data) calculation, which supports calculating all scalar types in SIMD Vector within a CPU instruction (currently Int, Float, Double, etc. are supported by default)
Collection Protocols
-
Swift collection types:
- Common:
- Array/ Dictionary/ Set
- Range / CloseRange for continuous range
- Rare:
- RangeSet for discrete ranges
- KeyValuePairs provides ordered key-value pairs that are lighter than dictionaries;
- CollectionOfOne: express the intent of the code more clearly and avoid allocating additional elements to reserve space.
- Common:
-
Swift collection protocols:
- Utility protocols for specific types of use cases:
- IteratorProtocol for iteration elements in Sequence.
- Strideable for index calculation and RandonAccessCollection.
- SetAlgebra for set related mathematical operation protocol.
- Sequence provides linear access to get elements by means of iterators (Sequence is not guaranteed to support multiple Iterator accesses; Complexity of accessing is O(n))
- Collection provides subscript, which supports access to O(1) by index (guaranteed multiple Iterator accesses at the same time)
- Further Offer BidirectionalCollection Supports reverse query of index(after) and reverse function
- Further Offer RandonAccessCollection Supports O(1) complexity indexing operations (move/distance/from, etc.)
- Mutability:
- MutableCollection, provides in place sort/shuffle/remove and other capabilities
- RangeReplacableCollection, provides the ability to replace any partial range in another Collection with a Collection of the same type.
- Lazy Iterator: (Exercise: Write a lazy iterator by hand):
- LazySequenceProtocol Defer collection-related calculations until the iterator is actually used, based on LasySequenceProtocol, and further provide LazyCollectionProtocol Supports access via the .lazy convenience function.
- Misc:
- Support types, which provide convenience encapsulation based on Dictionary/Sequence/Set/Range, etc.
- ManagedBuffer, used for performance optimization via adopting pointer-level continuous address access.
- Utility protocols for specific types of use cases: