首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >`case中的多个``case‘子句

`case中的多个``case‘子句
EN

Stack Overflow用户
提问于 2016-12-14 20:09:16
回答 1查看 1.1K关注 0票数 0

下面是代码(大部分是从http://codelle.com/blog/2016/5/an-easy-way-to-convert-swift-structs-to-json/复制的):

代码语言:javascript
复制
import Foundation

protocol JsonRepresentable {
    var JsonRepresentation: AnyObject {get}
}

protocol JsonSerializable: JsonRepresentable {
}

extension JsonSerializable {
    var JsonRepresentation: AnyObject {
        var representation = [String: AnyObject]()
        for case let (label?, value) in Mirror(reflecting: self).children {
            switch value {
            case let value as JsonRepresentable:
                representation[label] = value.JsonRepresentation
            case let value as NSNumber:
                representation[label] = value
            case let value as NSString:
                representation[label] = value
            case let value as NSArray:
                representation[label] = value
            case let value as NSDictionary:
                representation[label] = value
            case let value as NSNull:
                representation[label] = value
            default:
                break

            }
        }
        return representation as AnyObject
    }

    func toJson() -> String? {
        let representation = JsonRepresentation
        guard JSONSerialization.isValidJSONObject(representation) else {
            return nil
        }
        do {
            let data = try JSONSerialization.data(withJSONObject: representation, options: [])
            return String(data: data, encoding: String.Encoding.utf8)
        } catch {
            return nil
        }
    }
}

struct Owner: JsonSerializable {
    var name: String
}

struct Car: JsonSerializable {
    var manufacturer: String
    var model: String
    var mileage: Float
    var owner: Owner
}

let car = Car(manufacturer: "Kia", model: "K23", mileage: 143.3, owner: Owner(name: "娴静"))
print(car.toJson())

一切都如预期的那样工作,我唯一的问题是,NSString, NSNumber, NSArray等的分支完全相同。我如何避免这种冗余?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-14 20:19:11

而不是case let,您可以使用级联的is

代码语言:javascript
复制
extension JsonSerializable {
    var JsonRepresentation: Any {
        var representation = [String: Any]()
        for case let (label?, value) in Mirror(reflecting: self).children {
            switch value {
            case let value as JsonRepresentable:
                representation[label] = value.JsonRepresentation
            case is NSNumber, is NSString, is NSArray, is NSDictionary, is NSNull: representation[label] = value
            default:
                break

            }
        }
        return representation as Any
    }

 ....

假设JSON是Swift 3中的Any

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41151320

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档