Giter VIP home page Giter VIP logo

defaultcodable's Introduction

DefaultCodable

简介


DefaultCodable是基于Swift属性包装器实现的库,配合Codable使用可提高代码的健壮性。使用Codable解析Json数据时,有些字段可能为null或不存在,使用DefaultCodable可以指定属性的默认值,保证属性不为nil。另外如果Json含有未声明的枚举时,通常情况下会导致崩溃,设置@Default.FirstCase则会默认使用第一个枚举值。

示例

struct Model: Codable {
    // 枚举需遵循CaseIterable协议
    enum Category: String, Codable, CaseIterable {
        case unknown, oneCase, twoCase
    }
  
    // 标记title默认值为空字符串
    @Default.EmptyString
    var title: String
  
    // 标记comments默认值为空数组
    @Default.EmptyArray
    var comments: [Int]
  
    // 标记actions默认值为空字典
    @Default.EmptyDictionary
    var actions: [String: Bool]
  
    // 标记flag默认值为true
    @Default.True
    var flag: Bool
  
    // 标记count默认值为0
    @Default.Zero
    var count: Int

    // 标记value默认值为1
    @Default.One
    var value: Double
  
    // 注意:当使用FirstCase或者LastCase,对应的枚举类要遵循CaseIterable协议
    // 标记category1默认值为第一个枚举
    @Default.FirstCase
    var category1: Category
  
    // 标记category2默认值为最后一个枚举
    @Default.LastCase
    var category2: Category
}

defaultcodable's People

Contributors

moliya avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.