V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
iOS 开发实用技术导航
NSHipster 中文版
http://nshipster.cn/
cocos2d 开源 2D 游戏引擎
http://www.cocos2d-iphone.org/
CocoaPods
http://cocoapods.org/
Google Analytics for Mobile 统计解决方案
http://code.google.com/mobile/analytics/
WWDC
https://developer.apple.com/wwdc/
Design Guides and Resources
https://developer.apple.com/design/
Transcripts of WWDC sessions
http://asciiwwdc.com
Cocoa with Love
http://cocoawithlove.com/
Cocoa Dev Central
http://cocoadevcentral.com/
NSHipster
http://nshipster.com/
Style Guides
Google Objective-C Style Guide
NYTimes Objective-C Style Guide
Useful Tools and Services
Charles Web Debugging Proxy
Smore
dorentus
V2EX  ›  iDev

[ Swift 2.0]撸了一个 JSON 类型,欢迎拍砖

  •  
  •   dorentus · 2015-09-12 21:49:28 +08:00 · 2362 次点击
    这是一个创建于 3164 天前的主题,其中的信息可能已经有所发展或是发生改变。
    因为有了 indirect enum , Swift 终于可以直接表示这种递归的数据结构了

    支持 string 、 int 、 float 、 boolean 、 nil 、 array 、 dictionary literal ,然后加了个 initializer 来支持从 NSJSONSerialization 的 JSONObjectWithData (_, options:) 返回的 AnyObject 转成我的 JSON 数据结构

    代码如下:

    2 条回复    2015-09-13 20:47:43 +08:00
    wezzard
        1
    wezzard  
       2015-09-13 20:30:47 +08:00
    私以爲

    public subscript (index: Int ) -> JSON



    public subscript (key: Swift.String ) -> JSON

    返回 optional value 會比較好,實際過程中可能存在動態判斷,人爲 handle 一下比報 fatal error 要友好。
    wezzard
        2
    wezzard  
       2015-09-13 20:47:43 +08:00   ❤️ 1
    另外,爲甚麼要寫成

    for (k, v ) in zip (dictValue.keys, try dictValue.values.map { try JSON ($0 ) }) {
    dict[k] = v
    }


    而不是

    for (key, value ) in dictValue {
    dict[key] = try JSON (value )
    }



    zip 要 enumerate dictValue 的 keys 一遍,再 enumerate dictValue 的 values 一遍,然後生成的 sequence 再被你 enumerate 一遍,多 enumerate 了兩邊啊。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2692 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 65ms · UTC 04:22 · PVG 12:22 · LAX 21:22 · JFK 00:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.