Skip to content

Repository files navigation

SmartCodable

SmartCodable - Resilient & Flexible Codable for Swift

Latest ReleaseSwift 5.0+DocumentationSPM SupportedMIT LicenseAsk DeepWiki

English | 中文

SmartCodable enhances Apple's native Codable with production-ready resilience. When standard Codable fails on a single missing field or type mismatch, your entire model is lost. SmartCodable gracefully recovers — falling back to defaults, converting types automatically, and never interrupting the parse.

Why SmartCodable?

ScenarioStandard CodableSmartCodable
Missing key❌ Throws keyNotFound, entire model fails✅ Uses property initializer as default
Type mismatch (e.g., "123" for Int)❌ Throws typeMismatch, entire model fails✅ Auto-converts, returns 123
Null value for non-optional❌ Throws valueNotFound, entire model fails✅ Falls back to default value
Extra unknown keys✅ Ignored✅ Ignored

vs HandyJSON: SmartCodable builds on Apple's Codable protocol — no unsafe runtime reflection, no ABI stability risks. HandyJSON relies on Swift metadata reflection that may break across Swift versions.

vs Manual init(from:): SmartCodable eliminates the boilerplate of writing decodeIfPresent + ?? for every property. Same safety, zero ceremony.

Quick Start

import SmartCodable
structUser:SmartCodableX{varname:String=""varage:Int=0}
// ✅ Normal case
letuser=User.deserialize(from:["name":"John","age":30])
// User(name: "John", age: 30)
// ✅ Missing field — falls back to default
letuser2=User.deserialize(from:["name":"John"])
// User(name: "John", age: 0)
// ✅ Type mismatch — auto-converts
letuser3=User.deserialize(from:["name":"John","age":"30"])
// User(name: "John", age: 30)

To conform to SmartCodable, a class needs to implement an empty initializer:

classBasicTypes:SmartCodableX{varint:Int=2vardoubleOptional:Double?requiredinit(){}}letmodel=BasicTypes.deserialize(from: json)

For struct, the compiler provides a default empty initializer:

structBasicTypes:SmartCodableX{varint:Int=2vardoubleOptional:Double?}letmodel=BasicTypes.deserialize(from: json)

Installation

Swift Package Manager

dependencies:[.package(url:"https://github.com/iAmMccc/SmartCodable.git", branch:"main")]
  • SmartCodable provides the core parsing capabilities with no external dependencies.
  • For class inheritance via @SmartSubclass, see the companion package SmartCodableMacro.

CocoaPods (legacy)

Starting from 7.0, SmartCodable no longer ships via CocoaPods. If you must stay on CocoaPods, please use the 6.x series, which is preserved on the 6.1.0 branch:

pod'SmartCodable','~> 6.1'

The 6.x line will receive critical fixes only. All new features will land in 7.x and beyond — we strongly recommend migrating to Swift Package Manager.

Features

1. Deserialization

Only types conforming to SmartCodable (or [SmartCodable] for arrays) can use these methods:

publicstaticfunc deserialize(from dict:[String:Any]?, designatedPath:String?=nil, options:Set<SmartDecodingOption>?=nil)->Self?
public static func deserialize(from json:String?, designatedPath:String?=nil, options:Set<SmartDecodingOption>?=nil)->Self?
public static func deserialize(from data:Data?, designatedPath:String?=nil, options:Set<SmartDecodingOption>?=nil)->Self?
public static func deserializePlist(from data:Data?, designatedPath:String?=nil, options:Set<SmartDecodingOption>?=nil)->Self?

Multi-Format Input Support:

Input TypeExample UsageInternal Conversion
DictionaryModel.deserialize(from: dict)Directly processes native collections
Array[Model].deserialize(from: arr)Directly processes native collections
JSON StringModel.deserialize(from: jsonString)Converts to Data via UTF-8
DataModel.deserialize(from: data)Processes directly

Deep Path Navigation — Extract nested data directly:

// JSON: {"data": {"user": {"info": { ... }}}}
letmodel=Model.deserialize(from: json, designatedPath:"data.user.info")

Decoding Strategies:

letoptions:Set<SmartDecodingOption>=[.key(.convertFromSnakeCase),.date(.iso8601),.data(.base64)]letmodel=Model.deserialize(from: json, options: options)
Strategy TypeAvailable OptionsDescription
Key Decoding.fromSnakeCasesnake_case → camelCase
.firstLetterLower"FirstName" → "firstName"
.firstLetterUpper"firstName" → "FirstName"
Date Decoding.iso8601, .secondsSince1970, etc.Full Codable date strategies
Data Decoding.base64Binary data processing
Float Decoding.convertToString, .throwNaN/∞ handling

⚠️Important: Only one strategy per type is allowed (last one wins if duplicates exist)

2. Key Mapping

Map JSON keys to Swift property names. First non-null match wins:

staticfunc mappingForKey()->[SmartKeyTransformer]?{[CodingKeys.id <---["user_id","userId","id"],CodingKeys.name <---"nested.path.to.name" // nested path supported
]}

3. Value Transformation

Convert between JSON values and custom types:

staticfunc mappingForValue()->[SmartValueTransformer]?{[CodingKeys.url <---SmartURLTransformer(prefix:"https://"),CodingKeys.date <---SmartDateFormatTransformer(DateFormatter()),CodingKeys.status <---FastTransformer<Status,String>(
fromJSON:{Status(rawValue: $0 ??"")},
toJSON:{ $0?.rawValue }),]}

Built-in Transformers:

TransformerJSON → Object
SmartDateTransformerDouble/String → Date
SmartDateFormatTransformerString (custom format) → Date
SmartDataTransformerBase64 String → Data
SmartURLTransformerString → URL (with optional prefix & encoding)
SmartHexColorTransformerHex String → UIColor/NSColor

Need custom logic? Implement ValueTransformable:

publicprotocolValueTransformable{associatedtypeObjectassociatedtypeJSONfunc transformFromJSON(_ value:Any?)->Object?func transformToJSON(_ value:Object?)->JSON?}

4. Property Wrappers

WrapperPurposeExample
@SmartAnyAny, [Any], [String: Any] support@SmartAny var dict: [String: Any] = [:]
@SmartIgnoredSkip property during decoding@SmartIgnored var cache: String = ""
@SmartFlatFlatten nested object into parent@SmartFlat var profile: Profile?
@SmartPublishedCombine ObservableObject support@SmartPublished var name: String?
@SmartHexColorHex string → UIColor/NSColor@SmartHexColor var color: UIColor?
@SmartDateMulti-format date parsing@SmartDate var date: Date?
@SmartCompact.ArraySkip invalid array elements@SmartCompact.Array var ids: [Int]
@SmartCompact.DictionarySkip invalid dict entries@SmartCompact.Dictionary var info: [String: String]

@SmartAny example — support Any types that Codable can't handle natively:

structModel:SmartCodableX{@SmartAnyvardict:[String:Any]=[:]@SmartAnyvararr:[Any]=[]@SmartAnyvarany:Any?}letdict:[String:Any]=["dict":["name":"Lisa"],"arr":[1,2,3],"any":"Mccc"]letmodel=Model.deserialize(from: dict)
// Model(dict: ["name": "Lisa"], arr: [1, 2, 3], any: "Mccc")

@SmartIgnored example — skip property during decoding:

structModel:SmartCodableX{@SmartIgnoredvarname:String=""}letmodel=Model.deserialize(from:["name":"Mccc"])
// Model(name: "") — "name" was ignored, keeps default

@SmartFlat example — flatten nested fields into parent:

structModel:SmartCodableX{varname:String=""@SmartFlatvarprofile:Profile?}structProfile:SmartCodableX{varname:String=""varage:Int=0}
// JSON: {"name": "Mccc", "age": 18}
// profile gets name="Mccc", age=18 from the SAME level

@SmartCompact.Array example — tolerant array parsing:

structModel:Decodable{@SmartCompact.Arrayvarages:[Int]}
// JSON: {"ages": ["Tom", 1, {}, 2, 3, "4"]}
// Result: ages = [1, 2, 3, 4] (invalid elements skipped, "4" auto-converted)

5. Inheritance

Class inheritance support has been moved to a separate package — SmartCodableMacro. It depends on swift-syntax, so we ship it independently to keep this core library lightweight and dependency-free.

Add it alongside SmartCodable when you need @SmartSubclass:

dependencies:[.package(url:"https://github.com/iAmMccc/SmartCodableMacro.git", branch:"main")]

For inheritance usage on Swift versions prior to 5.9, see Inheritance in Lower Versions.

6. Enum Support

Simple enums — conform to SmartCaseDefaultable:

enumSex:String,SmartCaseDefaultable{case man
case woman
}

Enums with associated values — conform to SmartAssociatedEnumerable and provide a transformer via mappingForValue():

structModel:SmartCodableX{varsex:Sex=.man
staticfunc mappingForValue()->[SmartValueTransformer]?{[CodingKeys.sex <---SexTransformer()]}}enumSex:SmartAssociatedEnumerable{case man, woman, other(String)}structSexTransformer:ValueTransformable{typealiasObject=SextypealiasJSON=Stringfunc transformFromJSON(_ value:Any?)->Sex?{guardlet str = value as?Stringelse{returnnil}switch str {case"man":return.man
case"woman":return.woman
default:return.other(str)}}func transformToJSON(_ value:Sex?)->String?{nil}}

7. Post-Processing & Update

didFinishMapping() — runs after decoding completes:

structModel:SmartCodableX{varname:String=""mutatingfunc didFinishMapping(){
name ="I am \(name)"}}

SmartUpdater — update an existing model with new data:

varmodel=Model.deserialize(from: initialData)!
SmartUpdater.update(&model, from: newData)

8. Compatibility

SmartCodable handles parsing failures gracefully, ensuring the entire model never fails:

letdict=["number1":"123","number2":"Mccc","number3":"Mccc"]structModel:SmartCodableX{varnumber1:Int?varnumber2:Int?varnumber3:Int=1}
// Result: Model(number1: 123, number2: nil, number3: 1)
  • Type conversion: "123" (String) → 123 (Int) automatically
  • Default fill: When conversion fails, uses the property's initializer value (number3 = 1)
  • Optional handling: When conversion fails for optionals, returns nil (number2 = nil)

Performance tip for large data: When parsing very large datasets, avoid unnecessary compatibility overhead — use CodingKeys to exclude unused properties instead of @SmartIgnored, as it's more efficient.

9. Stringified JSON

SmartCodable auto-detects and parses string-encoded JSON:

structModel:SmartCodableX{varhobby:Hobby?}
// JSON: {"hobby": "{\"name\":\"sleep\"}"}
// hobby is parsed as Hobby(name: "sleep"), not a raw string

10. Debugging

SmartSentinel.debugMode =.verbose // .none | .verbose | .alert
SmartSentinel.onLogGenerated{ log inprint(log)}
================================ [Smart Sentinel] ================================
UserModel 👈🏻 👀
╆━ UserModel
┆┄ age : Expected Int, got String — auto-converted
┆┄ email : Key not found — using default ""
====================================================================================

Explore & Contribute

🔧 Migrate from HandyJSONStep-by-step migration guide
🛠 SmartModelerJSON → SmartCodable model generator
👀 SmartSentinelReal-time parsing log viewer
💖 ContributingSupport SmartCodable development
🏆 ContributorsKey contributors

FAQ

GitHub Stars

Stars

Join Community 🚀

SmartCodable is an open-source project dedicated to making Swift data parsing more robust, flexible and efficient. We welcome all developers to join our community!

JoinUs

About

SmartCodable is a data parsing library built on Swift’s Codable, designed for simple usage and strong real-world compatibility. It gracefully handles missing fields, default values, and evolving JSON structures. SmartCodable 是基于 Swift Codable 的数据解析库,主打简单易用与真实业务场景下的强兼容性,能够优雅应对不断变化的 JSON 数据。

Topics

Resources

Contributing

Stars

766 stars

Watchers

6 watching

Forks

Releases

Packages

Used by

Contributors

Languages