zoukankan      html  css  js  c++  java
  • Swift--加载本地资源文件并遍历

    开始上手Swift,之前的OC是门弱语言,而Swift是强语言,在语法上有较大的不同之处。

    // json文件
    [
     {
        "name": "json1",
        "title": "测试1",
     },
     {
         "name": "json2",
         "title": "测试2",
     },
     {
         "name": "json3",
         "title": "测试3",
     }
     ]
            /*
             * 加载本地文件
             */
            
            // 1.获取文件路径
            let path = NSBundle.mainBundle().pathForResource("plist.json", ofType: nil)
            // 2.通过文件路径创建NSData
            if let jsonPath = path {
                let jsonData = NSData(contentsOfFile: jsonPath)
                
                // 带throws的方法需要抛异常
                do {
                    /*
                     * 有可能发生异常的代码放在这
                     */
                    // 3.序列化 data -> array
                    /*
                     * try 和 try! 的区别
                     * try 发生异常会跳到catch代码中
                     * try! 发生异常程序会直接crash
                     */
                    let dictArr = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers)
                    // 4.遍历数组
                    // 在Swift中遍历数组,必须明确数据的类型 [[String: String]]表示字典里键值都是字符串 [[String]]表示数组里都是字符串
                    for dict in dictArr as! [[String: String]] {
                        
                        print(dict)
                    }
                }catch {
                    // 异常代码放在这
                    print(error)
                }
            }
  • 相关阅读:
    STM32固件库和自定义工程模板
    STM32存储器映射和寄存器映射
    VScode搭建OpenCV环境
    手写数字识别——基于LeNet-5卷积网络模型
    敏感信息泄露
    Google的高级搜索——Google hack
    session fixation攻击
    认证和会话管理漏洞
    SQLmap
    基于时间型SQL盲注
  • 原文地址:https://www.cnblogs.com/zhangshan/p/5700662.html
Copyright © 2011-2022 走看看